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
| class Solution { public int shortestPathBinaryMatrix(int[][] grid) { if(grid[0][0]==1||grid[grid.length-1][grid[0].length-1]==1)return -1; int[][] skipped=new int[grid.length][grid[0].length]; int floor=1,cnt=0; int[] element; int r,c,ir,ic; int[][] action={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; for(r=0;r<grid.length;r++){ for(c=0;c<grid[r].length;c++){ if(grid[r][c]==1)skipped[r][c]=1; } } Queue<int[]> queue=new LinkedList<>(); queue.add(new int[]{0,0}); while(!queue.isEmpty()){ cnt=queue.size(); while(cnt>0){ element=queue.remove(); skipped[element[0]][element[1]]=1; if(element[0]==grid.length-1&&element[1]==grid[0].length-1){ return floor; } for(int i=0;i<action.length;i++){ ir=element[0]+action[i][0]; ic=element[1]+action[i][1]; if(ir>=0&&ir<grid.length&&ic>=0&&ic<grid[ir].length){ if(skipped[ir][ic]==0){ queue.add(new int[]{ir,ic}); skipped[ir][ic]=1; } } } cnt--; } floor++; }
return -1; } }
|