LeetCode - 542 - 01 Matrix

5 篇文章 0 订阅
4 篇文章 0 订阅

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.

Subscribe to see which companies asked this question.


题意:0/1矩阵,对于每个1求出离他最近的0需要走多少步

思路:就一个简单的bfs,纯的,裸的,特别裸。。。

心情好复杂啊。。。搞清楚了以后觉得自己是个zz,这么简单的面试题我居然写了暴力。。。(求面试官心理阴影面积T T)

class Solution {
public:
    struct node {
        int x, y;
        node() {}
        node (int _x, int _y) {
            x = _x;
            y = _y;
        }
    };
    vector<vector<int>> updateMatrix(vector<vector<int>>& a) {
        int c = a.size(), r = a[0].size();
        vector<vector<int>> ans(c, vector<int>(r, r + c));
        queue<node> m;
        for (int i = 0; i < c; i++) {
            for (int j = 0; j < r; j++) {
                if (a[i][j] == 0) {
                    m.push(node(i, j));
                    ans[i][j] = 0;
                }
            }
        }
        int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
        while (!m.empty()) {
            node now = m.front();
            m.pop();
            for (int i = 0; i < 4; i++) {
                int nx = now.x + dir[i][0];
                int ny = now.y + dir[i][1];
                while (nx >=0 && nx < c && ny >= 0 && ny < r && ans[nx][ny] == r + c) {
                    m.push(node(nx, ny));
                    ans[nx][ny] = ans[now.x][now.y] + 1;
                }
            }
        }
        return ans;
    }
};


啊,再贴个男票写的~

vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
    int n = matrix.size(),m = matrix[0].size();
    vector<vector<int>> res(n,vector<int>(m,n+m));
    queue<pair<int,int>> Q;
    for(int i=0;i<n;++i)
        for(int j=0;j<m;++j)
            if(matrix[i][j] == 0) Q.push(make_pair(i,j)),res[i][j] = 0;

    int dx[] = {0,0,1,-1};
    int dy[] = {1,-1,0,0};
    
    while(!Q.empty()) {
        auto u = Q.front(); Q.pop();
        for(int i=0;i<4;++i){
            int x = u.first + dx[i],y = u.second + dy[i];
            if(x >= 0 && y >= 0 && x < n && y < m && res[x][y] == m+n){
                res[x][y] = res[u.first][u.second] + 1;
                Q.push(make_pair(x,y));
            }
        }
    }
    return res;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值