ansan @ 2024-01-22 15:41:12
using namespace std;
const int N = 50;
bool vis[N][N];
int dx[4] = {1, -1, 0, 0};
long long dy[4] = {0, 0, 1, -1};
long long cha[50][50];
long long a[50][50];
long long n;
void dfs(int x, int y){
for(int i = 0; i < 4; i++){
int xx = x + dx[i], yy = y + dy[i];
if(xx >= 0 && xx <= n+1 && yy >= 0 && yy <= n+1 && !vis[xx][yy]){
vis[xx][yy] = 1;
cha[xx][yy] = -1;
dfs(xx,yy);
vis[xx][yy] = 0;
}
}
return;
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cin >> a[i][j];
if(a[i][j] == 1)
vis[i][j] = 1;
}
}
vis[0][0] = 1;
dfs(0,0);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(a[i][j] == 0 && cha[i][j] != -1)
a[i][j] = 2;
cout << a[i][j] << " ";
}
cout << "\n";
}
return 0;
}
by mooktian @ 2024-01-23 10:34:08
我帮你改了下,你自己看看。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 50;
bool vis[N][N];
int dx[4] = {1, -1, 0, 0};//方向下上左右
int dy[4] = {0, 0, 1, -1};
//long long cha[50][50];
int a[50][50];
int n;
void dfs(int x, int y){
for(int i = 0; i < 4; i++){
int xx = x + dx[i], yy = y + dy[i];
if(xx >= 0 && xx <= n+1 && yy >= 0 && yy <= n+1 && !vis[xx][yy] && a[xx][yy] != 1){//a[xx][yy] =1可以看成是墙,就不走
vis[xx][yy] = 1;
//cha[xx][yy] = -1;
dfs(xx,yy);
//给矩阵外围多加一圈0,对于每个为0的点,只走一次,所以不需要回溯
//vis[xx][yy] = 0;
}
}
return;
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cin >> a[i][j];
//if(a[i][j] == 1)
//vis[i][j] = 1;
}
}
vis[0][0] = 1;
dfs(0,0);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
//if(a[i][j] == 0 && cha[i][j] != -1)
if(a[i][j] == 0 && vis[i][j] == 0)
a[i][j] = 2;
cout << a[i][j] << " ";
}
cout << "\n";
}
return 0;
}