Loading…
Loading…
Expands the closest unsettled node first using a priority queue, giving the shortest path even when cells have different costs (weights).
Start distance = 0.
1dist[start] = 0; // Start distance is zero2pq.add(new int[]{0, start}); // Push start into the PQ3while (!pq.isEmpty()) { // Until priority queue empty4 int[] top = pq.poll(); int node = top[1]; // Pop the nearest cell5 if (settled[node]) continue; // Skip stale duplicates6 settled[node] = true; // Lock in its distance7 if (node == goal) return buildPath(); // Goal found — trace path8 for (int neighbor : neighbors(node)) { // Scan passable neighbors9 int alt = dist[node] + cost(neighbor); // Distance via this cell10 if (alt < dist[neighbor]) { // Found a shorter route11 dist[neighbor] = alt; parent[neighbor] = node; // Relax and record parent12 pq.add(new int[]{alt, neighbor}); // Re-queue with new key13 }14 }15}16 17List<Integer> neighbors(int cell) { // Passable 4-neighbors18 int r = cell / COLS, c = cell % COLS;19 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};20 List<Integer> out = new ArrayList<>();21 for (int[] d : dirs) {22 int nr = r + d[0], nc = c + d[1];23 if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) continue;24 int nbr = nr * COLS + nc;25 if (!walls.contains(nbr)) out.add(nbr);26 }27 return out;28}29 30int cost(int cell) { // Step cost to enter a cell31 return weights.contains(cell) ? WEIGHT_COST : 1;32}33 34List<Integer> buildPath() { // Walk parent back from goal35 List<Integer> path = new ArrayList<>();36 for (int at = goal; at != -1; at = parent[at]) path.add(at);37 Collections.reverse(path);38 return path;39}