01 Matrix

127 篇文章 0 订阅

01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

Example 1: 
Input:

0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0

Example 2: 
Input:

0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.
解析:

开始用dfs,runtime error ,是后面的点可能依赖前面点的结果,觉得dfs是可行的,只是自己写的代码有问题,后来用bfs,还是擅长bfs,用dfs实现的可以交流一下。。。。QAQ..

代码:

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        if (matrix.empty()) return {};
        int rows=matrix.size();
        int cols=matrix[0].size();
        vector<vector<int> > ans (rows,vector<int>(cols,0));
        queue<pair<int,int>>que;
        
        for (int i=0; i<rows; i++)
        {
            for (int j=0; j<cols; j++)
            {
                if (matrix[i][j]==0)
                 que.push(make_pair(i,j));
            }
        }
        int dx[4]={0,1,0,-1};
        int dy[4]={-1,0,1,0};
        while (!que.empty())
        {
            int posy=que.front().first;
            int posx=que.front().second;
            for (int k=0; k<4; k++)
            {
                int tempy=posy+dy[k];
                int tempx=posx+dx[k];
                if (tempy<0||tempx<0||tempy>=rows||tempx>=cols)
                {
                    continue;
                }
                if (matrix[tempy][tempx]==0||ans[tempy][tempx]) continue;
                ans[tempy][tempx]=ans[posy][posx]+1;
                que.push(make_pair(tempy,tempx));
            }
            que.pop();
        }
        
        return ans;
    }
    
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值