Leetcode 5053. 地图分析 (150周赛)

5053. 地图分析

你现在手里有一份大小为 N x N 的『地图』(网格) grid,上面的每个『区域』(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,你知道距离陆地区域最远的海洋区域是是哪一个吗?请返回该海洋区域到离它最近的陆地区域的距离。

我们这里说的距离是『曼哈顿距离』( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。

如果我们的地图上只有陆地或者海洋,请返回 -1

示例 1:

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

示例 2:

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

提示:

  1. 1 <= grid.length == grid[0].length <= 100
  2. grid[i][j] 不是 0 就是 1

    运用广度优先搜索,首先将所有的大陆都加入堆栈,同时从每个大陆开始进行广度优先搜索,保证到达的每个海洋都是离最近的大陆的最短距离,记录期间的最大距离作为最后的输出。

class Solution {
public:
	int dir_x[4] = { -1,0,0,1 };
	int dir_y[4] = { 0,1,-1,0 };
	int N = 0 ,Res = -1;
	struct Road {
		int x, y;
		int len;
		Road(int xx, int yy, int ll) {
			x = xx; y = yy; len = ll;
		}
	};

	queue<Road>store;
	bool flag[101][101];
	void BFS()
	{
		while (!store.empty())
		{
			Road front = store.front();
			Res = front.len;
            //cout << Res<<endl;
			for (int i = 0; i < 4; i++)
			{
				int xx = front.x + dir_x[i];
				int yy = front.y + dir_y[i];
                //cout << xx <<" y= "<<yy<<endl;
				if (xx>=0 && xx < N &&  yy>=0  && yy < N && flag[xx][yy] == 0)
				{
                    flag[xx][yy] = 1;
                    cout << xx <<" y= "<<yy<<endl;
					store.push(Road(xx, yy, front.len + 1));
				}
			}
			store.pop();
		}

	}
	int maxDistance(vector<vector<int>>& grid) {
		N = grid[0].size();
        cout <<N<<endl;
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < N; j++)
			{
				if (grid[i][j] == 1)
				{
					store.push(Road(i , j, 0));
					flag[i][j] = 1;
				}
                else
                    flag[i][j] = 0;
			}
		}
		BFS();
		if (Res == 0)
			return -1;
		else
			return Res;
	}
};
发布了104 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Yanpr919/article/details/99707185
今日推荐