n*n格子,由三种字符:
- 点’.'表示平地
- 星‘*’ 表示障碍物
- '#'表示房子。
需要在某些地方(平地或房子)建商店,商店不能建在障碍物。
最终要使得每一个房子出发到都可以到达商店,求商店数量的最小值,在商店数最少的情况下求每个房子到商店的最小距离
输入:n 表示格子大小,char[][]格子
输出:最小的商店数量,和最小的距离
- 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;
}