BFS训练Leetcode#994腐烂的橘子
问题描述
思路分析
代码1:采用BFS遍历同时记录下每个健康橘子的感染源,再记录下最后一个被感染的健康橘子。
通过对最后一个健康橘子的感染路径回溯,计算出所花费的时间。
(最初的思路是记录下最后一个健康橘子的坐标比较它和初始感染源橘子集合中每个橘子的距离,找到最短距离计算时间,这个方法误以为最后一个橘子一定是被距离他最近的腐烂橘子所感染了。)
代码2(leetcode代码):通过对每一波感染的处理,记录感染波,在最终波被感染时通过波数反应感染时间。
代码1
#include"law.h";
class Solution {
bool visit[10][10];
const int move[4][2] = { {-1,0},{1,0},{0,1},{0,-1} };
vector<prdd>vi;
queue<prdd>q;
int freshleft;
prdd lastfind;
prdd fnode[10][10];
int intime;
void time(prdd a) {
if (a.first != -1) {
time(fnode[a.first][a.second]);
cout << a.first << "," << a.second << endl;
intime++;
}
}
public:
int orangesRotting(vector<vector<int>>& grid) {
memset(visit, false, sizeof(visit));
memset(fnode, (-1, -1), sizeof(fnode));
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
if (grid[i][j] == 2) {
q.push(prdd{ i,j });
visit[i][j] == true;
vi.push_back(prdd{ i,j });
}
if (grid[i][j] == 1) {
freshleft++;
}
}
}
cout << freshleft;
while (!q.empty()) {
prdd tmp = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int a = tmp.first + move[i][0];
int b = tmp.second + move[i][1];
cout << 'z';
if (a > -1 && a<grid.size() && b>-1 && b < grid[0].size() && grid[a][b] == 1 && visit[a][b] == false) {
prdd tmpe = { a,b };
fnode[a][b] = tmp;
q.push(tmpe);
visit[a][b] = true;
freshleft--;
cout << freshleft << endl;
if (freshleft == 0) {
lastfind = { a,b };
break;
}
}
}
/* if (freshleft == 0) { break; }*/
}
if (freshleft == 0) {
if (!vi.empty()) {
time(lastfind);
return intime - 1;
}
else return 0;
}
else return -1;
}
};
int main() {
vector<vector<int>> grid;
vector<int> griden;
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int t;
cin >> t;
griden.push_back(t);
}
grid.push_back(griden);
griden.clear();
}
Solution sol;
cout<<sol.orangesRotting(grid);
}
代码2
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int dirs[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int row = grid.size();
int colum = grid[0].size();
queue<pair<int,int>> q;
int count = 0;
int time = 0;
for (int i=0;i<row;i++) {
for (int j=0;j<colum;j++) {
if (grid[i][j] == 1)
count++;
else if (grid[i][j] == 2)
q.push({i,j});
}
}
if (count == 0)
return 0;
while (!q.empty()) {
time++;
for (int j=q.size();j>0;j--) {
auto cur = q.front();
q.pop();
for (int k=0;k<4;k++) {
int x = cur.first + dirs[k][0];
int y = cur.second + dirs[k][1];
if (x<0 || x>row-1 || y<0 || y>colum-1 || grid[x][y] == 0)
continue;
if (grid[x][y] == 1) {
count--;
grid[x][y] = 2;
q.push({x,y});
}
}
if (count == 0)
return time;
}
}
return -1;
}
};