LeetCode 1162. map analysis (BFS)

1. Topic

You now have a hand of size N x N's "map" (grid) grid, above each "area" (cells) are labeled with 0 and 1 well. Where 0 represents the ocean, 1 on behalf of the land, you know marine areas farthest from land areas which one it is?

Please return the area to the ocean from the nearest land areas.

We are speaking here of distance "Manhattan distance" (Manhattan Distance) :( x0, y0) and (x1, y1) the distance between the two regions is | x0 - x1 | + | y0 - y1 |.

If we map the ocean or land only, please return -1.

Example 1:
Here Insert Picture Description

输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释: 
海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2

Example 2:
Here Insert Picture Description

输入:[[1,0,0],[0,0,0],[0,0,0]]
输出:4
解释: 
海洋区域 (2, 2) 和所有陆地区域之间的距离都达到最大,最大距离为 4。
 
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j] 不是 0 就是 1

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/as-far-from-land-as-possible
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

  • BFS standard template title, queue, visited an array of records access status
class Solution {
public:
    int maxDistance(vector<vector<int>>& grid) {
    	int m = grid.size(), n = grid[0].size();
    	int i, j, x0, y0, x, y, k, count = 0, dis = 0, size;
    	vector<vector<bool>> visited(m, vector<bool>(n,false));
    	queue<vector<int>> q;
    	vector<vector<int>> dir = {{1,0},{0,1},{0,-1},{-1,0}};
    	for(i = 0; i < m; ++i)
    	{
    		for(j = 0; j < n; ++j)
    		{
    			if(grid[i][j])
    			{
    				q.push({i,j});
    				visited[i][j] = true;
    				count++;
    			}
    		}
    	}
    	if(count==0 || count==m*n)
    		return -1;
    	while(!q.empty())
    	{
    		size = q.size();
    		while(size--)
    		{
    			x0 = q.front()[0];
    			y0 = q.front()[1];
                q.pop();
    			for(k = 0; k < 4; ++k)
    			{
    				x = x0 + dir[k][0];
    				y = y0 + dir[k][1];
    				if(x>=0 && x<m && y>=0 && y<n && !visited[x][y])
    				{
    					q.push({x,y});
    					visited[x][y] = true;
    				}
    			}
    		}
    		dis++;
    	}
    	return dis-1;
    }
};

Here Insert Picture Description

Published 784 original articles · won praise 1143 · Views 310,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105172033