KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
What I'm trying to do is count how many moves it takes to get to the goal using the shortest path. It must be done using a breadth first search. I put the 8x8 grid into a 2d array which is filled with one of four chars, E for empty (can move into these spots), B for blocked (can't move here), R for robot (starting point), or G for goal. The algorithm had to check for movable spaces in the order up, left, right, then down, which I believe I've done correctly. After a node is checked it changes its contents to a 'B'. If the goal cannot be reached, 0 should be returned. I have changed my code to implement what Kshitij told me, and it works beautifully. I was just too tired to see that I wasn't initializing my queue after every new data set lol. Thanks for the help! public static int bfSearch(){ Queue <int []> queue = new LinkedList <int []> (); int [] start = {roboty,robotx,0}; queue.add(start); while (queue.peek() != null){ int [] array = queue.remove(); if(array[0]-1 >= 0 && grid[array[0]-1][array[1]] != 'B'){ if (grid[array[0]-1][array[1]] == 'G'){ return array[2]+1; } else{ grid[array[0]-1][array[1]] = 'B'; int [] temp = {array[0]-1, array[1], array[2]+1}; queue.add(temp); } } if(array[1]-1 >= 0 && grid[array[0]][array[1]-1] != 'B'){ if (grid[array[0]][array[1]-1] == 'G'){ return array[2]+1; } else{ grid[array[0]][array[1]-1] = 'B'; int [] temp = {array[0], array[1]-1, array[2]+1}; queue.add(temp); } } if(array[1]+1 <= 7 && grid[array[0]][array[1]+1] != 'B'){ if (grid[array[0]][array[1]+1] == 'G'){
Tags (comma-separated)
Save Edits
Cancel