542. 01 矩阵(多源bfs)

链接:542. 01 矩阵 - 力扣(LeetCode)

题解:

cpp 复制代码
class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
	int m = mat.size();
	if (m <= 0) {
	    return {};
	}
	int n = mat[0].size();
	if (n <= 0) {
	    return {};
	}
	vector<vector<int>> result(m, vector<int>(n, 0));
	unordered_map<int, int> dist;
	queue<int> que;
	for (int i = 0; i < m; ++i) {
	    for (int j = 0; j < n; ++j) {
		if (mat[i][j] == 0) {
		    que.push(i*n+j);
		    dist[i*n+j] = 0;
		}
	    }
	}
	vector<vector<int>> direc{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
	while (!que.empty()) {
	    auto f = que.front();
	    que.pop();
	    for (auto& d : direc) {
		int next_row = f/n + d[0];
		int next_col = f%n + d[1];
		if (next_row < 0 || next_col < 0 || next_row >= m || next_col >= n) {
		    continue;
		}
		int node = next_row * n + next_col;
		if (dist.find(node) != dist.end()) {
		    continue;
		}
		dist[node] = dist[f] + 1;
		result[next_row][next_col] = dist[node];
        que.push(node);
	    }
	}
	return result;
    }
};