算法分析与设计丨第十一周丨Sicily(15)—— 1003. 最近的0(Hard)

题目描述:

输入一个N*M的01矩阵A,对矩阵的每个位置,求至少经过多少步可以到达一个0. 每一步可以往上下左右走一格.

 
请为下面的Solution类实现解决这一问题的函数nearestZero,函数参数A为给出的01矩阵,A的行数和列数均不大于100. 函数的返回值是问题的答案.
 
class Solution {
public:
    vector<vector<int>> nearestZero(vector<vector<int>>& A) {
                        
    }
};
 
例如:
A=
1 1 1
0 1 1
0 0 1
 
答案为
1 2 3
0 1 2
0 0 1

题目解析:这次期中测试的题目,当时时间不够没有写出来,用广度优先搜索,注意放入队列当中的条件,还有matrix的设置。


// Problem#: 21103
// Submission#: 5210377
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
class Solution {
public:
    vector<vector<int>> nearestZero(vector<vector<int> >& A) {
            
            int row_size = A.size();
            if(row_size == 0)
                return A;
            int col_size = A[0].size();

            vector<vector<int>> result(row_size,vector<int>(col_size,100000));

            int position[4][2] = {{0,-1},{0,1},{1,0},{-1,0}};

            queue<pair<int,int> > my_que;

            for(int i = 0; i < row_size; ++i)
                for(int j = 0; j < col_size; ++j)
                {
                    if(A[i][j] == 0)
                    {
                        result[i][j] = 0;
                        my_que.push({i,j});
                    }
                }

            while(!my_que.empty())
            {
                pair<int,int> cur = my_que.front();
                my_que.pop();

                for(int i = 0; i < 4; ++i)
                {
                    int next_row = cur.first + position[i][0],next_col = cur.second + position[i][1];
                    if(next_row >= 0 && next_col >= 0 && next_row < row_size && next_col < col_size)
                    {
                        if(result[next_row][next_col] > result[cur.first][cur.second] + 1)
                        {
                            result[next_row][next_col] = result[cur.first][cur.second] + 1;
                            my_que.push({next_row,next_col});
                        }
                    }
                }


            }



            return result;

                     
    }


};                                 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值