Problem #23 [Easy]

This problem was asked by Google.

You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on.

Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.

For example, given the following board:

[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row.
求最短路径,bfs即可。

int updateMatrix(vector<vector<char>>& arr) {
        int stp = 1, m = arr.size(), n = arr[0].size(),x,y;
        queue<pair<int,int>> que;
        int start[2] ={3,0}, end[2] ={0,0};
        int directions[4][2] ={{0,1}, {0,-1},{1,0},{-1,0} };
        que.push({start[0], start[1]});
        while(!que.empty()){
            int sz = que.size();
            for(int i=0;i<sz;i++){
                auto cur = que.front();
                que.pop();
                for(auto dir:directions){
                    x = cur.first+dir[0];
                    y = cur.second+dir[1];
                    if( x<0 || x >= m || y<0 ||y>=n || arr[x][y] == 't') continue;
                    if(x== end[0] and y == end[1]) {return stp;}
                    que.push({x,y});
                    arr[x][y] = 1;
                }   
            }
            stp++;
        }
        return 0;
    }
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值