Google Interview - 警察到房间的最短距离

9 篇文章 0 订阅
6 篇文章 0 订阅

一个 n x n 矩阵,每个房间可能是封闭的房间,可能是警察,可能是开的房间, 封闭的房间不能过,返回一个n x n矩阵,每一个元素是最近的警察到这个房间的最短距离。 初始矩阵中-1代表封闭房间,INT_MAX代表普通房间,0代表有警察的房间。

 

Solution: 把警察都找出来,然后一起push到BFS的queue里面,同时搜索。复杂度可降为O(n^2)。

Starting from police and override the distance with smaller value if multiple polices can reach the same office. 

void police_and_rooms(vector<vector<int>>& rooms) {
    int n = (int)rooms.size();
    if (n == 0) return;
    
    set<pair<int,int>> visited;
    queue<pair<int,int>> q;
    queue<int> dists;
    
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            if (rooms[i][j] == 0) {
                q.push({i,j});
                visited.insert({i,j});
                dists.push(0);
            }
        }
    }
    while(!q.empty()) {
        auto pos = q.front();
        q.pop();
        
        auto dist = dists.front();
        dists.pop();
        
        vector<pair<int,int>> dirs =  {{0,1}, {0,-1}, {1,0}, {-1,0}};
        for(auto dir : dirs) {
            pair<int,int> cur = {dir.first + pos.first, dir.second + pos.second};
            if(cur.first < 0 || cur.second < 0 || cur.first >= n || cur.second >= n)
                continue;
            
            if(visited.count(cur)) continue;
            if(rooms[cur.first][cur.second] == -1) {
                visited.insert(cur);
                continue;
            }
            
            visited.insert(cur);
            
            dists.push(dist + 1);
            q.push(cur);
            
            rooms[cur.first][cur.second] =
            min(rooms[cur.first][cur.second], dist + 1);
        }
    }
}

 

Reference:

http://www.mitbbs.com/article_t/JobHunting/32767115.html

http://www.fgdsb.com/2015/01/03/police-and-rooms/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值