994. 腐烂的橘子(Leetcode)(多源BFS)

994. 腐烂的橘子

难度简单85

在给定的网格中,每个单元格可以有以下三个值之一:

  • 值 0 代表空单元格;
  • 值 1 代表新鲜橘子;
  • 值 2 代表腐烂的橘子。

每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。

返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1

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

	queue <R> store;
	int Flag[11][11];
	int N , M, count = 0;
	int record = 0;
	int BFS()
	{
		while (!store.empty())
		{
			R front = store.front();
			for (int i = 0; i < 4; i++)
			{
				int xx = front.x + dir_x[i];
				int yy = front.y + dir_y[i];
				if (xx >= 0 && xx < N &&  yy >= 0 && yy < M && Flag[xx][yy] == 1)
				{
					record++;
					if (record == count)
						return front.len;
					Flag[xx][yy] = 2;
					store.push(R(xx, yy, front.len + 1));
				}
			}
			store.pop();
		}
        if(record < count)
            return -1;
        else
            return 0;
	}
	int orangesRotting(vector<vector<int>>& grid) {
		N = grid.size();
		M = grid[0].size();
		for (int i = 0; i < N; ++i)
		{
			for (int j = 0; j < M; ++j)
			{
				Flag[i][j] = grid[i][j];
				if (grid[i][j] == 1)
					count++;
				else if(grid[i][j] == 2)
					store.push(R(i, j, 1));
			}
		}
		return(BFS());
	}
};
发布了104 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Yanpr919/article/details/104647394