2
public int shortestPathBinaryMatrix(int[][] grid) {3
int m = grid.length, n = grid[0].length;5
boolean[][] visited = new boolean[m][n];7
int[] up = {0, 0, 1, -1, 1, 1, -1, -1};8
int[] down = {-1, 1, 0, 0, -1, 1, -1, 1};11
if top-left is 1 or bottom-right is 114
if (grid[0][0] == 1 || grid[m - 1][n - 1] == 1) return -1;16
ArrayDeque<int[]> q = new ArrayDeque<>();18
we will add top-left to the deque21
q.add(new int[] {0, 0, 1});23
while (q.size() > 0) {24
int[] tmp = q.removeFirst();30
if (x == m - 1 && y == n - 1) return steps;32
for (int i = 0; i < 8; i++) {33
int x_new = x + up[i];34
int y_new = y + down[i];36
we will traverse level wise using bfs37
and those which can be directly reach via38
current level will be considered as the same39
level and we will return the level of40
bottom-right as result42
if (x_new >= 0 && x_new < m && y_new >= 0 && y_new < n) {43
if (visited[x_new][y_new] == false && grid[x_new][y_new] == 0) {44
q.add(new int[] {x_new, y_new, steps + 1});45
visited[x_new][y_new] = true;