leetcode+图上BFS,一次性过的+注意二维vector赋值问题
点击打开链接
//一次性过的 #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <cstring> #include <string.h> #include <algorithm> #include <vector> #include <numeric> #include <limits> #include <math.h> #include <queue> using namespace std; class Solution { struct Node{ int x, y; int steps; }; int Move[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; queue<Node>Q; public: int BFS(int xx, int yy, int row, int col, vector< vector<int> >& matrix) { int vis[row+1][col+1]; memset(vis, 0, sizeof(vis)); while (!Q.empty()) Q.pop(); Node temple1, temple2; temple1.x=xx; temple1.y=yy; temple1.steps=0; Q.push(temple1); while (!Q.empty()) { temple1=Q.front(); Q.pop(); if(matrix[temple1.x][temple1.y]==0) return temple1.steps; for(int i=0;i<4;i++){ temple2=temple1; temple2.x+=Move[i][0]; temple2.y+=Move[i][1]; if(temple2.x>=0&&temple2.x<row&& temple2.y>=0&&temple2.y<col&&!vis[temple2.x][temple2.y]){ vis[temple2.x][temple2.y]=1; temple2.steps+=1; Q.push(temple2); } } } return 0; } vector< vector<int> > updateMatrix(vector< vector<int> >& matrix) { int row=matrix.size(), col=matrix[0].size(); int res[row+1][col+1]; vector< vector<int> >re; vector<int> temp; int i,j; for(i=0;i<row;i++){ for(j=0; j<col;j++){ if(matrix[i][j]==0){ res[i][j]=0; } else res[i][j]=BFS(i,j,row, col,matrix); } } for(i=0;i<row;i++){ for(j=0;j<col;j++){ temp.push_back(res[i][j]); } re.push_back(temp); temp.clear(); } return re; } }; int main() { return 0; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。