2021-09-27腾讯笔试第五题

n*n格子,由三种字符:

  • 点’.'表示平地
  • 星‘*’ 表示障碍物
  • '#'表示房子。
    需要在某些地方(平地或房子)建商店,商店不能建在障碍物。
    最终要使得每一个房子出发到都可以到达商店,求商店数量的最小值,在商店数最少的情况下求每个房子到商店的最小距离

输入:n 表示格子大小,char[][]格子
输出:最小的商店数量,和最小的距离

  1. List item
#include<iostream>
#include<vector>
#include<queue>
#include<bits/stdc++.h>
using namespace  std;

const int maxn = 50 +10 ;
char s[maxn][maxn];
int color[maxn][maxn];
int n;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
bool vis[maxn*maxn];
void dfs(int i, int j, int col){
    color[i][j] = col;
    for(int p = 0; p < 4; p++){
        int x = i + dx[p];
        int y = j + dy[p];
        if(x < 0 || x >= n || y < 0 || y >= n ||s[x][y] == '*' || color[x][y]) continue;
        dfs(x, y, col);
    }
}


int solve (int col){
    vector<int> house;
    for (int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if (color[i][j] == col) {
                house. push_back(i * n + j);
            }
        }
    }
    if(house.empty()) return 0;
//    int  tot = n * n * n * n;
    int tot = INT_MAX;
    for(int i = 0 ; i< house.size(); i++){
        for (int p= 0; p < n * n; p++){
            vis[p] = false;
        }
        vis[house[i]] = true;
        queue<pair<int,int>>q;
        q.push(make_pair(house[i],0));
        int ans = 0 ;
        while(!q.empty()){
            auto pa = q.front();
            q.pop();
            int x = pa.first /n;
            int y = pa.first % n;
            int c = pa.second;
            if(s[x][y] == '#')  ans += c;
            if(ans >= tot) break;
            for(int p = 0; p < 4; p++){
                int newx = x + dx[p];
                int newy = y + dy[p];
                if(newx < 0 || newx >= n|| newy < 0 || newy >= n|| s[newx][newy] == '*'|| vis[newx * n + newy]) continue;
                vis[newx * n + newy] = true;
                q.push(make_pair(newx*n + newy, c+1));
            }

        }
        tot = min(tot, ans) ;
    }
    return tot;

}
int main(){

    cin >> n;
    for (int i = 0; i < n; i++) cin >> s[i];

    int tot = 0;
    for (int i = 0; i < n; i++){
        for(int j = 0; j < n; j++) {
            if (s[i][j] == '#' && !color[i][j]){
                dfs(i, j, ++tot);
            }

        }
    }


    int dis = 0;
    for (int i = 1; i <= tot; i++) {
        dis += solve(i);
    }
    cout <<tot<<" "<< dis <<endl;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值