LeeCode 1162 地图分析(每日打卡)
程序员文章站
2022-07-15 12:22:46
...
BFS解法
class Solution {
public:
int n, m;
int MAXN = 1005;
int vis[105][105];
int dx[5] = {-1, 0, 1, 0};
int dy[5] = {0, 1, 0, -1};
struct Node
{
int x, y, step;
};
vector< vector<int> > a;
int bfs(int x, int y)
{
queue<Node> q;
memset(vis, 0, sizeof(vis));
struct Node now;
now.x = x;
now.y = y;
now.step = 0;
q.push(now);
while(!q.empty())
{
auto tmp = q.front();
q.pop();
for(int i = 0; i < 4; ++i)
{
int fx = tmp.x + dx[i];
int fy = tmp.y + dy[i];
if(!((fx >= 0 && fx < this->m) && (fy >= 0 && fy < this->n)))
{
continue;
}
if(vis[fx][fy] == 0)
{
vis[fx][fy] = 1;
q.push({fx, fy, tmp.step + 1});
if(a[fx][fy] == 1)
{
return tmp.step + 1;
}
}
}
}
return -1;
}
int maxDistance(vector<vector<int>>& grid) {
this->m = grid[0].size();
this->n = grid.size();
int ans = -1;
a = grid;
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if(a[i][j] == 0)
ans = max(ans, bfs(i, j));
}
}
return ans;
}
};
上一篇: leetcode 1162. 地图分析
下一篇: LeetCode 1162. 地图分析