LG1605
C++
#include<iostream>
using namespace std;
#define N 10000
int map[N][N]= {0},book[N][N]= {0},n,m,bar;
int startx,starty,endx,endy,ans=0;
int next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
void dfs(int x,int y) {
int i,tx,ty;
if(x==endx&&y==endy) {
ans++;
return;
} else {
for(i=0; i<=3; i++) {
tx=x+next[i][0];
ty=y+next[i][1];
if(tx<1||ty<1||tx>n||ty>m)
continue;
else if(map[tx][ty]==0&&book[tx][ty]==0) {
book[tx][ty]=1;
dfs(tx,ty);
book[tx][ty]=0;
}
}
}
return;
}
int main() {
int a,b;
cin>>n>>m>>bar;
cin>>startx>>starty>>endx>>endy;
while(bar--) {
cin>>a>>b;
map[a][b]=2;
}
map[startx][starty]=1;
dfs(startx,starty);
cout<<ans;
return 0;
}
Tips
1、在使用深度优先搜索的时候,要先把起点先在map中标记,防止后面重复走。
map[startx][starty]=1;
2、在dfs中重新设置下一步的tx,ty,而不能直接在原来的x,y上进行更新。
3、变量i不可以设置在全局变量中,之前一次因为这个原因耽搁了半天,每一次的递归中i应该是独立的。
4、在写代码的时候注意地图n,m表示的是行还是列(细节决定成败)。
5、第一个return;用于调用的返回,若缺失,导致程序无法停止报错。