You are viewing a single comment's thread. Return to all comments →
public static int minimumMoves(List<String> grid, int startX, int startY, int goalX, int goalY) { // Write your code here int[][] DIRS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int N = grid.size(); boolean[][] visited = new boolean[N][N]; Queue<int[]> queue = new LinkedList(); queue.offer(new int[]{startX,startY}); int moves = 0; while (!queue.isEmpty()){ int size = queue.size(); moves++; for (int i=0; i<size; i++){ int[] pair = queue.poll(); int x = pair[0], y = pair[1]; for (int[] dir: DIRS){ int nextX = x; int nextY = y; while (true){ nextX += dir[0]; nextY += dir[1]; if (nextX < 0 || nextX >= N || nextY >=N || nextY < 0 || grid.get(nextX).charAt(nextY) == 'X') break; if (nextX == goalX && nextY == goalY){ return moves; } else if (! visited[nextX][nextY]){ visited[nextX][nextY] = true; queue.offer(new int[]{nextX, nextY}); } } } } } return -1; }
Seems like cookies are disabled on this browser, please enable them to open this website
Castle on the Grid
You are viewing a single comment's thread. Return to all comments →