1162.地图分析

这题有意思,这个BFS的精髓在起点,起点是全部的岛屿点。知道了这点就能看懂网上其它到题解了

class Solution {
public:
class pos
{
public:
	int x;
	int y;
	pos(int xx,int yy):x(xx),y(yy){};
};

    int maxDistance(vector<vector<int>>& grid) {
        	queue<pos>a;
	int m=grid.size();
	int n=grid[0].size();
	vector<vector<int>> b;
	b.assign(grid.begin(),grid.end());
	for(int i=0;i<m;++i)
	{
		for(int j=0;j<n;++j)
		{
			if(1==grid[i][j])
		 	{
				pos temp(i,j);
				a.push(temp);
				b[i][j] = 0;
			}
			else
			{
				b[i][j] = -1;
			}
		}
	}
	int maxx = -1;
	if(n*m == (int)a.size())
	  return -1;
	int count=0;
	while(!a.empty())
	{
		++count;
		pos temp = a.front();
		int i=temp.x;
		int j = temp.y;
		
		if(i-1 >= 0 && -1 == b[i-1][j])
		{
			b[i-1][j] = b[i][j]+1;
			maxx=max(maxx,b[i-1][j]);
			pos newtemp(i-1,j);
			a.push(newtemp);
		}
		if(j-1 >= 0 && -1 == b[i][j-1])
		{
			b[i][j-1] = b[i][j]+1;
			maxx = max(maxx,b[i][j-1]);
			pos newtemp(i,j-1);
			a.push(newtemp);
		}
		if(i+1<m && -1==b[i+1][j])
		{
			b[i+1][j] = b[i][j]+1;
			maxx = max(maxx,b[i+1][j]);
			pos newtemp(i+1,j);
			a.push(newtemp);
		}
		if(j+1<n && -1==b[i][j+1])
		{
			b[i][j+1] = b[i][j]+1;
			maxx = max(maxx,b[i][j+1]);
			pos newtemp(i,j+1);
			a.push(newtemp);
		}
		a.pop();
	}
	return maxx;

    }
};
发布了21 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qigezuishuaide/article/details/103115281