【攻克力扣200题--32】1091. 二进制矩阵中的最短路径

mac2024-11-09  8

BFS,在宝宝的帮助下,顺利地写出了这题,开心

var shortestPathBinaryMatrix = function(grid) { if(grid[0][0]==1) return -1; let direction=[[1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]]; let queue=[]; let m=grid.length,n=grid[0].length; let pathLength=0; queue.push([0,0]); while(queue.length>0){ var size=queue.length; pathLength++; while(size-->0){ var cur=queue.shift(); var cr=cur[0],cc=cur[1]; if(cr==m-1&&cc==n-1) return pathLength; for(var i=0;i<8;i++){ var nr=cr+direction[i][0],nc=cc+direction[i][1]; if(nr<0||nc<0||nr>=m||nc>=n||grid[nr][nc]==1) continue; grid[nr][nc]=1; queue.push([nr,nc]); } } } return -1; };

 

最新回复(0)