Flooding problems (bfs application)

Title Description

A nxm matrix shape in the city's outbreak of floods, flooding from (0,0) flows to the city grid, in this matrix there are some buildings and some plaid, plaid flow not only flood the building. Please return to the flood flow (n - 1, m - 1) the earliest time (flood flows only from one of its neighboring lattice grid and grid flood flow per unit time from a contiguous grid).

Given a matrix map showing the city in which map [i] [j] represents the coordinates (i, j) grid, the grid has a value of 1 for building, building 0 representing no. While a given size of the matrix n and m (n and m are less than or equal to 100), return flow (n - 1, m - 1 ) the earliest time. Ensure that the flood will be able to flow to the end.

class Flood {
public:
    int visited[102][102]={0};
    int offset[4][2]={1,0,0,1,-1,0,0,-1};
    int floodFill(vector<vector<int> > map, int n, int m) {
        int step=0;
        bfs(map,n,m,step);
        return step;
    }
private:
    void bfs(vector<vector<int> >&map,int &n,int &m,int &step)
    {
        queue<pair<int,int> >q;
        q.push(pair<int,int>(0,0));
        while(!q.empty())
        {
            ++step;
            int size=q.size();
            for(int i=0;i<size;++i)
            {
                pair<int,int>f=q.front();
                q.pop();
                visited[f.first][f.second]=1;
                for(int i=0;i<4;++i)
                {
                    int tx=f.first+offset[i][0];
                    int ty=f.second+offset[i][1];
                    if(tx==n-1&&ty==m-1) return ;
                   if(tx<0||tx>=n||ty<0||ty>=m||map[tx][ty]==1||visited[tx][ty]==1)
                        continue;
                    q.push(pair<int,int>(tx,ty));
                }
            }
        }
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_43871369/article/details/93406405