牛客_洪水算法题

题目描述

在一个nxm矩阵形状的城市里爆发了洪水,洪水从(0,0)的格子流到这个城市,在这个矩阵中有的格子有一些建筑,洪水只能在没有建筑的格子流动。请返回洪水流到(n - 1,m - 1)的最早时间(洪水只能从一个格子流到其相邻的格子且洪水单位时间能从一个格子流到相邻格子)。

给定一个矩阵map表示城市,其中map[i][j]表示坐标为(i,j)的格子,值为1代表该格子有建筑,0代表没有建筑。同时给定矩阵的大小nm(n和m均小于等于100),请返回流到(n - 1,m - 1)的最早时间。保证洪水一定能流到终点。

 

解:简单的BFS,使用结构体来表示节点,将访问过的元素标记为-1。

 

#include<bits/stdc++.h>
using namespace std;

struct Node
{
    int x, y;
    int step = 0;
};

int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};

class Flood {
public:
    int floodFill(vector<vector<int> > map, int n, int m) {
        queue<Node> q;
        Node first;
        first.x = 0;
        first.y = 0;
        first.step = 0;
        q.push(first);
        map[0][0] = -1;
        while(!q.empty())
        {
            Node temp = q.front();
            q.pop();
            if(temp.x == n - 1 && temp.y == m - 1)
            {
                return temp.step;
            }
            for(int i = 0; i < 4; i++)
            {
                Node mid;
                mid.x = temp.x + dx[i];
                mid.y = temp.y + dy[i];
                mid.step = temp.step + 1;
                if(mid.x >= 0 && mid.x < n && mid.y >= 0 && mid.y < m && map[mid.x][mid.y] == 0)
                {
                    q.push(mid);
                    map[mid.x][mid.y] = -1;
                }
            }
        }
        return 0;
    }
};

int main()
{
    vector<vector<int> > mp(100, vector<int>(100, 0));
    Flood f;
    cout << f.floodFill(mp, 100, 100) << endl;
    return 1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值