好久没做dfs了,都快忘了emm;大概思路是对的,但要记得标记已走过的位置,以及障碍在终点的情况的特判定;判断坐标越界的方法;申明函数里面的变量要写,不然会报错。
#include <bits/stdc++.h>
using namespace std;
int n, m, t;
int sx, sy, fx, fy;
int i, j, k;
int bx, by;
int a[6][6];
int ans = 0;
int main() {
cin >> n >> m >> t;
cin >> sx >> sy >> fx >> fy;
for (i = 1; i <= t; i++) {
cin >> bx >> by;
a[bx][by] = 1;//标记障碍
}
if (a[fx][fy] == 1) {
cout << "0";
return 0;
}
void dfs(int x, int y);
dfs(sx, sy);
cout << ans;
}
void dfs(int x, int y) {
if (x < 1 || x > n) //x坐标越界
return;
if (y < 1 || y > m) //y坐标越界
return;
if (x == fx & y == fy) {
ans++;
return ;
} else if (a[x][y] == 1 || a[x][y] == 2)
return ;
else {
a[x][y] = 2;
dfs(x + 1, y);
dfs(x, y + 1);
dfs(x, y - 1);
dfs(x - 1, y);
a[x][y] = 0;
}
return ;
}