Loading…
Loading…
Explores the grid in expanding rings from the start, guaranteeing the fewest-steps path on an unweighted grid.
Enqueue the start node.
1Queue<Integer> queue = new ArrayDeque<>(); // Frontier of cells to visit2queue.add(start); visited[start] = true; // Seed with the start cell3while (!queue.isEmpty()) { // Until frontier is empty4 int node = queue.poll(); // Take oldest queued cell5 if (node == goal) return buildPath(); // Goal found — trace path6 for (int neighbor : neighbors(node)) // Scan passable neighbors7 if (!visited[neighbor]) { // Skip already-seen cells8 visited[neighbor] = true; parent[neighbor] = node; // Mark and record parent9 queue.add(neighbor); // Enqueue for later10 }11}12 13List<Integer> neighbors(int cell) { // Passable 4-neighbors14 int r = cell / COLS, c = cell % COLS;15 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};16 List<Integer> out = new ArrayList<>();17 for (int[] d : dirs) {18 int nr = r + d[0], nc = c + d[1];19 if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;20 int nbr = nr * COLS + nc;21 if (!walls.contains(nbr)) out.add(nbr);22 }23 return out;24}25 26List<Integer> buildPath() { // Walk parent back from goal27 List<Integer> path = new ArrayList<>();28 for (int at = goal; at != -1; at = parent[at]) path.add(at);29 Collections.reverse(path);30 return path;31}