思路
BFS,对每个出口标记走k步能到达的点,然后记录每个点的距离。如果有某个点在之前的出口被标记走过且距离要大于当前的出口到这个点的距离的话,那么就将该点的距离更新为离当前出口最近的距离。
#include <cstdio>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3+7;
typedef long long ll;
struct Node
{
int x,y,s;
};
int dir[4][2] = {{0,1},{-1,0},{1,0},{0,-1}};
vector<int>G[maxn];
vector<Node>A;
vector<Node>res;
bool vis[maxn][maxn];
int dist[maxn][maxn];
void bfs(int x, int y, int k, int n, int m) {
queue<Node>q;
Node t;
t.x = x;
t.y = y;
t.s = 0;
q.push(t);
while(!q.empty()) {
Node now = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
Node tmp;
tmp.x = now.x + dir[i][0];
tmp.y = now.y + dir[i][1];
tmp.s = now.s + 1;
if (vis[tmp.x][tmp.y] && dist[tmp.x][tmp.y] > tmp.s) {
vis[tmp.x][tmp.y] = 0;
}
//cout << tmp.x << " " << tmp.y << " " << endl;
if (tmp.x >= 0 && tmp.x < n && tmp.y >= 0 && tmp.y < m && tmp.s <= k && G[tmp.x][tmp.y] == 0 && !vis[tmp.x][tmp.y]) {
res.push_back(tmp);
vis[tmp.x][tmp.y] = 1;
dist[tmp.x][tmp.y] = tmp.s;
q.push(tmp);
}
}
}
}
int main() {
int k;
cin >> k;
char s;
int x;
int n = 0;
// !cin.eof()
//int t = 16;
while(!cin.eof()){
cin >> x;
s = getchar();
G[n].push_back(x);
if (s == '\n') ++n;
//G[n].push_back(x);
}
//int n = (int)G.size();
int m = (int)G[0].size();
//cout << m << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < (int)G[0].size(); ++j) {
vis[i][j] = 0;
dist[i][j] = maxn*maxn;
//cout << G[i][j] << " ";
if (G[i][j] == 1) {
Node tmp;
tmp.x = i;
tmp.y = j;
A.push_back(tmp);
dist[i][j] = 0;
//cout << i <<" "<< j << endl;
}
}
//cout << endl;
}
for (int i = 0; i < (int)A.size(); ++i) {
//cout << A[i].x << " " << A[i].y << endl;
bfs(A[i].x, A[i].y, k, n, m);
}
for (int i = 0; i < (int)res.size(); ++i) {
int x = res[i].x;
int y = res[i].y;
G[x][y] = 0;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (G[i][j] == -1 || G[i][j] == 1) cout << "0";
else if (G[i][j] == 0 && vis[i][j] == 0) cout << "1";
else cout << G[i][j];
if (j != m-1) cout << ",";
else cout << endl;
}
}
return 0;
}
/*
3
0,-1,1,0
0,0,0,-1
0,-1,0,-1
1,-1,0,0
*/