-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixBFS.java
More file actions
49 lines (43 loc) · 1.57 KB
/
MatrixBFS.java
File metadata and controls
49 lines (43 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package Recursion;
import java.util.ArrayDeque;
import java.util.Deque;
public class MatrixBFS {
//Matrix (2D Grid)
int[][] grid = {{0, 0, 0, 0},
{1, 1, 0, 0},
{0, 0, 0, 1},
{0, 1, 0, 0}};
// Shortest path from top left to bottom right
public int bfs(int[][] grid) {
int ROWS = grid.length;
int COLS = grid[0].length;
int[][] visit = new int[ROWS][COLS];
Deque<int[]> queue = new ArrayDeque<>();
queue.add(new int[2]); // Add {0, 0}
visit[0][0] = 1;
int length = 0;
while (!queue.isEmpty()) {
int queueLength = queue.size();
for (int i = 0; i < queueLength; i++) {
int[] pair = queue.poll();
int r = pair[0], c = pair[1];
if (r == ROWS - 1 && c == COLS - 1) {
return length;
}
// We can directly build the four neighbors
int[][] neighbors = {{r, c + 1}, {r, c - 1}, {r + 1, c}, {r - 1, c}};
for (int j = 0; j < 4; j++) {
int newR = neighbors[j][0], newC = neighbors[j][1];
if (Math.min(newR, newC) < 0 || newR == ROWS || newC == COLS
|| visit[newR][newC] == 1 || grid[newR][newC] == 1) {
continue;
}
queue.add(neighbors[j]);
visit[newR][newC] = 1;
}
}
length++;
}
return length; // This should never be called
}
}