Given a knight in a chessboard (a binary matrix with 0 as empty and 1 as barrier) with a source position, find the shortest path to a destination position, return the length of the route.
Return -1 if knight can not reached.
Given a 2D grid, each cell is either a wall 2, a zombie 1 or people 0 (the
number zero, one, two).
Zombies can turn the nearest people(up/down/left/right) into zombies every day,
but can not through wall.
How long will it take to turn all people into zombies? Return -1 if can not turn
all people into zombies.
Given a matrix:
0 1 2 0 0
1 0 0 2 1
0 1 0 0 0
return 2
structPoint{intx;inty;Point(intxx,intyy):x(xx),y(yy){}};intzombie(vector<vector<int>>&grid){introws=grid.size();intcols=grid[0].size();queue<Point>q;intres=0,people=0;intdir[4][2]={-1,0,0,1,1,0,0,-1};for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){if(grid[i][j]==1)q.push(Point(i,j));if(grid[i][j]==0)people++;}}while(!q.empty()){if(people==0)returnres;res++;// move on one step
for(inti=q.size();i--;i>0){Pointcur=q.front();q.pop();for(intj=0;j<4;j++){intnextx=cur.x+dir[j][0];intnexty=cur.y+dir[j][1];if(nextx<0||nextx>=rows||nexty<0||nexty>=cols)continue;if(grid[nextx][nexty]==2||grid[nextx][nexty]==1)continue;grid[nextx][nexty]=2;// 不能重放2次
q.push(Point(nextx,nexty));people--;}}}return-1;}
近期评论