leetcode 542——01矩阵

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;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值