Loading…
Loading…
Always expands the node that looks closest to the goal by heuristic alone. Very fast and targeted, but its path is not guaranteed to be shortest.
Seed the open set with the start.
1open.add(new int[]{h(start), start}); queued[start] = true; // Seed open by heuristic h2while (!open.isEmpty()) { // Until open set is empty3 int node = open.poll()[1]; // Pop cell closest to goal4 if (visited[node]) continue; // Skip if already visited5 if (node == goal) return buildPath(); // Goal found — trace path6 visited[node] = true; // Mark cell visited7 for (int neighbor : neighbors(node)) // Scan passable neighbors8 if (!visited[neighbor] && !queued[neighbor]) { // Only brand-new cells9 parent[neighbor] = node; queued[neighbor] = true; // Record parent, mark queued10 open.add(new int[]{h(neighbor), neighbor}); // Queue by h alone11 }12}13 14int h(int cell) { // Manhattan distance to goal15 int r = cell / COLS, c = cell % COLS;16 int gr = goal / COLS, gc = goal % COLS;17 return Math.abs(r - gr) + Math.abs(c - gc);18}19 20List<Integer> neighbors(int cell) { // Passable 4-neighbors21 int r = cell / COLS, c = cell % COLS;22 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};23 List<Integer> out = new ArrayList<>();24 for (int[] d : dirs) {25 int nr = r + d[0], nc = c + d[1];26 if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;27 int nbr = nr * COLS + nc;28 if (!walls.contains(nbr)) out.add(nbr);29 }30 return out;31}32 33List<Integer> buildPath() { // Walk parent back from goal34 List<Integer> path = new ArrayList<>();35 for (int at = goal; at != -1; at = parent[at]) path.add(at);36 Collections.reverse(path);37 return path;38}