题目链接:https://leetcode-cn.com/problems/01-matrix
题目描述:
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
题解:
将多源广度优先搜索转化为单源广度优先搜索。将所有的0看成一个整体,添加超级0。任意一个 1 到它最近的 0 的距离
解题链接:https://leetcode-cn.com/problems/01-matrix/solution/01ju-zhen-by-leetcode-solution/
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
//查找元素到0 的最近距离
queue<pair<int,int>> que;
int m = mat.size();
int n = mat[0].size();
vector<vector<int>> result(m, vector<int>(n));
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(mat[i][j] == 0) //
{
result[i][j] = 0;
que.push(pair(i, j));
}
}
}
int dist = 0;
//上下左右四个方位
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
while(!que.empty())
{
dist++;
int len = que.size();
for(int i = 0; i < len; i++ )
{
pair<int,int> temp = que.front();
que.pop();
for(int j = 0; j < 4; j++)
{
int row = temp.first + dx[j];
int col = temp.second + dy[j];
if(row >=0 && row < mat.size() && col >=0 && col < mat[0].size() && mat[row][col] == 1)
{
mat[row][col] = 0;
result[row][col] = dist;
que.push(make_pair(row, col));
}
}
}
}
return result;
}
};