-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1091. Shortest Path in Binary Matrix.java
84 lines (65 loc) · 2.08 KB
/
1091. Shortest Path in Binary Matrix.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
class Point{
int x;
int y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
class Node{
Point pt;
int dist;
Node(Point pt, int dist)
{
this.pt = pt;
this.dist = dist;
}
}
public int shortestPathBinaryMatrix(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
if(grid[0][0] != 0 || grid[rows-1][cols-1] != 0)
return -1;
Point src = new Point(0,0);
Point dest = new Point(rows-1, cols-1);
int dist = bfs(grid, src, dest);
return dist;
}
int bfs(int[][] grid, Point src, Point dest)
{
int rowNum[] = {1, 1, 0, -1, -1, -1, 0, 1};
int colNum[] = {0, 1, 1, 1, 0, -1, -1, -1};
int rows = grid.length;
int cols = grid[0].length;
System.out.println(rows + " " + cols);
boolean vis[][] = new boolean[rows][cols];
vis[src.x][src.y] = true;
Node qnode = new Node(src, 1);
Queue<Node> q = new LinkedList<>();
q.add(qnode);
while(!q.isEmpty())
{
Node curr = q.peek();
Point pt = curr.pt;
System.out.println(pt.x + " " + pt.y);
if(pt.x == dest.x && pt.y == dest.y)
return curr.dist;
q.remove();
for(int i = 0; i < 8; i++)
{
int row = pt.x + rowNum[i];
int col = pt.y + colNum[i];
System.out.println(row + " " + col);
if(row >= 0 && row < rows && col >= 0 && col < cols && !vis[row][col] && grid[row][col] == 0)
{
vis[row][col] = true;
Node adjnode = new Node(new Point(row, col), curr.dist + 1);
q.add(adjnode);
}
}
}
return -1;
}
}