2021-04-20-仙途实习-笔试题

文章目录

1. 描述

给定一张栅格地图,求每个格子离最近的障碍物的距离。

Example 1:
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]

Example 2:
Input:
[[1,1,1],
[1,0,1],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]

Leetcode 542 01矩阵

2. 代码

class Solution {
public:
    vector<vector<int> > updateMatrix(vector<vector<int> >& grid){
        int rows = grid.size();
        int cols = grid[0].size();
        vector<vector<int> > dist(rows, vector<int>(cols, 0));
        vector<vector<int> > mark(rows, vector<int>(cols, 0));

        queue<pair<int, int> > Q;
        
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                if(grid[i][j] == 0){
                    Q.push(make_pair(i, j));
                    mark[i][j] = 1;
                }
            }
        }

        const int dx[4] = { -1, 1, 0, 0 };
        const int dy[4] = { 0, 0, -1, 1 };

        while(!Q.empty()){
            int x = Q.front().first;
            int y = Q.front().second;
            Q.pop();

            for(int i = 0; i < 4; i++){
                int newx = x + dx[i];
                int newy = y + dy[i];
                if(newx >= 0 && newx < rows && 
                   newy >= 0 && newy < cols && mark[newx][newy] == 0){
                    dist[newx][newy] = dist[x][y] + 1;
                    Q.push(make_pair(newx, newy));
                    mark[newx][newy] = 1;
                }
            }
        }
        return dist;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值