Loading…
Loading…
Like Dijkstra, but a heuristic pulls the search toward the goal — so it settles far fewer cells while still finding the shortest path.
Seed the open set with the start.
1g[start] = 0; // Cost from start is zero2open.add(new int[]{h(start), start}); // Seed open set by f = h3while (!open.isEmpty()) { // Until open set is empty4 int node = open.poll()[1]; // Pop lowest-f cell5 if (settled[node]) continue; // Skip stale duplicates6 settled[node] = true; // Lock in this cell7 if (node == goal) return buildPath(); // Goal found — trace path8 for (int neighbor : neighbors(node)) { // Scan passable neighbors9 int tentativeG = g[node] + cost(neighbor); // Cost to reach via node10 if (tentativeG < g[neighbor]) { // Found a cheaper route11 g[neighbor] = tentativeG; parent[neighbor] = node; // Relax and record parent12 open.add(new int[]{tentativeG + h(neighbor), neighbor}); // Queue by f = g + h13 }14 }15}16 17int h(int cell) { // Manhattan distance to goal18 int r = cell / COLS, c = cell % COLS;19 int gr = goal / COLS, gc = goal % COLS;20 return Math.abs(r - gr) + Math.abs(c - gc);21}22 23List<Integer> neighbors(int cell) { // Passable 4-neighbors24 int r = cell / COLS, c = cell % COLS;25 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};26 List<Integer> out = new ArrayList<>();27 for (int[] d : dirs) {28 int nr = r + d[0], nc = c + d[1];29 if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;30 int nbr = nr * COLS + nc;31 if (!walls.contains(nbr)) out.add(nbr);32 }33 return out;34}35 36int cost(int cell) { // Step cost to enter a cell37 return weights.contains(cell) ? WEIGHT_COST : 1;38}39 40List<Integer> buildPath() { // Walk parent back from goal41 List<Integer> path = new ArrayList<>();42 for (int at = goal; at != -1; at = parent[at]) path.add(at);43 Collections.reverse(path);44 return path;45}