这个的代码用dfs怎么写,我写的这个老是出错,求指教
#include
using namespace std;
#define endl '\n'
int a[100][100],b[100][100],min1=99999999,step1=0,n;
void dfs(int x1,int y1,int step);
int main(){
int n1,n2,a1,a2;
scanf ("%d",&n);
for (n1=0;n10;n2"%d",&a[n1][n2]);
if (a[n1][n2]==-1){
a1=n1;
a2=n2;
}
}
}
dfs(a1,a2,0);
cout<0;
}
void dfs(int x1,int y1,int step){
if (a[x1][y1]==-2){
if (step1]==0&&x11)1]=1;
dfs(x1,y1+1,step+a[x1][y1+1]);
b[x1][y1+1]=0;
}
else if (b[x1+1][y1]==0&&(x1+1)1][y1]=1;
dfs(x1+1,y1,step+a[x1+1][y1]);
b[x1+1][y1]=0;
}
else if (b[x1][y1-1]==0&&x1-1)-1]=1;
dfs(x1,y1-1,step+a[x1][y1-1]);
b[x1][y1-1]=0;
}
else if (b[x1-1][y1]==0&&(x1-1)-1][y1]=1;
dfs (x1-1,y1,step+a[x1-1][y1]);
b[x1-1][y1]=0;
}
return;
}
谢谢!
考虑每个可达状态的方式是基本正确的,但需要注意以下几点:
在dfs的过程中防止越界,比如x1和y1都必须小于n才能继续向下递归。
对已经访问过的格子做标记,避免重复搜索。注意一定要在回溯时解除标记。
在dfs的过程中,step参数代表当前位置到起点的敌人数量之和,不要直接加上a[x1][y1]后继续向下递归,因为这一步只代表走到了一个新的位置,而不代表已经遇到了新的敌人。
根据以上几点需要对dfs函数进行如下修改:
void dfs(int x1, int y1, int step) {
if (a[x1][y1] == -2) {
if (step < min1) {
min1 = step;
}
return;
}
if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= n || b[x1][y1] == 1) {
// 越界或者已经访问过该位置,直接返回
return;
}
b[x1][y1] = 1; // 标记已经访问过的位置
// 搜索四个方向
dfs(x1, y1+1, step + a[x1][y1]);
dfs(x1+1, y1, step + a[x1][y1]);
dfs(x1, y1-1, step + a[x1][y1]);
dfs(x1-1, y1, step + a[x1][y1]);
b[x1][y1] = 0; // 回溯时解除标记
}