01 Matrix 01 矩阵

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例 1: 
输入:

0 0 0
0 1 0
0 0 0

输出:

0 0 0
0 1 0
0 0 0

示例 2: 
输入:

0 0 0
0 1 0
1 1 1

输出:

0 0 0
0 1 0
1 2 1

注意:

  1. 给定矩阵的元素个数不超过 10000。
  2. 给定矩阵中至少有一个元素是 0。
  3. 矩阵中的元素只在四个方向上相邻: 上、下、左、右。

思路:采用BFS,但是这道题和传统的BFS不太一样,传统的BFS都会以queue为辅助,每次取q.size()作为外循环的次数,因为q的队列里存储的都是性质相同的元素。但是这道题不太一样,首先把matrix中为0的元素的下标加到q中,且初始化元素为0的元素为0,其他元素为INT_MAX。然后每次取出q的一个元素,考察它的四个方向(上下左右)的值和(当前下标的值+1)的值谁大,如果对应方向的值更大,就更新为当前下标的值+1(相当于那个方向有可能会成为一个新的拓展节点),并把对应的方向放入新的队列中。

参考代码:

class Solution {
public:
void updateMatrixCore(vector<vector<int>>& matrix, queue<pair<int, int>> &q, vector<vector<int>> &res) {
	int direction[4][2] = { {-1,0},{1,0},{0,1},{0,-1} };
	while (!q.empty()) {
		pair<int, int> pair = q.front(); q.pop();
		for (int i = 0; i < 4; i++) {
			int new_r = pair.first + direction[i][0], new_c = pair.second + direction[i][1];		
			if (new_r >= 0 && new_r < matrix.size() && new_c >= 0 && new_c < matrix[0].size()) {
				if (res[new_r][new_c] > (res[pair.first][pair.second] + 1)) {
					res[new_r][new_c] = res[pair.first][pair.second] + 1;
					q.push(make_pair(new_r,new_c));
				}
			}
		}
	}
}
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
	if (matrix.empty()) return {};
	vector<pair<int, int>> zeros;
	vector<vector<int>> res(matrix.size(), vector<int>(matrix[0].size(), INT_MAX));
	queue<pair<int, int>> q;
	for (int i = 0; i < matrix.size(); i++) {
		for (int j = 0; j < matrix[0].size(); j++) {
			if (matrix[i][j] == 0) {
				q.push(make_pair(i, j));
				res[i][j] = 0;
			}
		}
	}
	updateMatrixCore(matrix, q,res);
	return res;
}
};
扫描二维码关注公众号,回复: 3345295 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/82817124