LeeCode 1162 地图分析(每日打卡)

在这里插入图片描述
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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值