leetcode 542——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
注意:
给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/01-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
提交:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int rows = matrix.size(); //matrix的行数
int cols = matrix[0].size(); //matrix的列
queue<pair<int,int>> position;
for(int i=0;i<rows;++i)
{
for(int j=0;j<cols;++j)
{
if(matrix[i][j] == 0) position.push(pair<int,int>(i,j));
else matrix[i][j] = INT_MAX; //这里要进行一下标记
//不然后面会重复入队
//在这耗了好长时间........
}
}
pair<int,int> directions[4] = {{1,0},{-1,0},{0,1},{0,-1}};
while(!position.empty())
{
pair<int,int> pos = position.front(); position.pop();
int x = pos.first;
int y = pos.second;
for(int i=0;i<4;++i)
{
int nx = x + directions[i].first,ny = y + directions[i].second;
if(nx>=0&&nx<rows&&ny>=0&&ny<cols&&matrix[nx][ny] == INT_MAX)
{
matrix[nx][ny] = matrix[x][y] + 1;
position.push(pair<int,int>(nx,ny));
}
}
}
return matrix;
}
};