0% found this document useful (0 votes)
3 views

generalDijikstra

The document contains a Java class named Pathfinding that implements Dijkstra's algorithm to find the shortest path in a grid. It initializes a distance array, uses a priority queue to explore possible paths, and updates distances based on movement until boundaries or obstacles are encountered. The method returns the shortest distance to the destination or -1 if unreachable.

Uploaded by

20cse0129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

generalDijikstra

The document contains a Java class named Pathfinding that implements Dijkstra's algorithm to find the shortest path in a grid. It initializes a distance array, uses a priority queue to explore possible paths, and updates distances based on movement until boundaries or obstacles are encountered. The method returns the shortest distance to the destination or -1 if unreachable.

Uploaded by

20cse0129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.util.

PriorityQueue;
import java.util.Arrays;

class Pathfinding {
public int findPath(int[][] grid, int[] start, int[] destination) {
int rows = grid.length, cols = grid[0].length;

// Step 1: Initialize auxiliary array


int[][] distances = new int[rows][cols];
for (int[] row : distances) Arrays.fill(row, Integer.MAX_VALUE);
distances[start[0]][start[1]] = 0;

// Step 2: Priority Queue for Dijkstra's Algorithm


PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.offer(new int[]{0, start[0], start[1]}); // {distance, row, col}

// Step 3: Directions for movement


int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

// Step 4: Process the queue


while (!pq.isEmpty()) {
int[] current = pq.poll();
int dist = current[0], r = current[1], c = current[2];

// If already processed with shorter distance, skip


if (dist > distances[r][c]) continue;

// Explore all directions


for (int[] dir : directions) {
int nr = r, nc = c, steps = 0;

// Move in the direction until hitting a boundary/obstacle


while (nr + dir[0] >= 0 && nr + dir[0] < rows &&
nc + dir[1] >= 0 && nc + dir[1] < cols &&
grid[nr + dir[0]][nc + dir[1]] == 0) {
nr += dir[0];
nc += dir[1];
steps++;
}

// Update distance if a shorter path is found


int newDist = dist + steps;
if (newDist < distances[nr][nc]) {
distances[nr][nc] = newDist;
pq.offer(new int[]{newDist, nr, nc});
}
}
}

// Step 5: Return result


return distances[destination[0]][destination[1]] == Integer.MAX_VALUE ? -
1 : distances[destination[0]][destination[1]];
}
}

You might also like