![image](https://img2022.cnblogs.com/blog/2674359/202208/2674359-20220807224120425-91750165.png)
DFS 求方案个数
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 100 + 10;
int n, m, x, y;
bool st[N][N];
int res;
int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2};
int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1};
void dfs(int x, int y, int cnt)
{
if (cnt == n * m) {
res ++;
return;
}
st[x][y] = true;
for (int i = 0; i < 8; i ++) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m || st[a][b])
continue;
dfs(a, b, cnt + 1);
}
st[x][y] = false;
}
void solve()
{
cin >> n >> m >> x >> y;
memset(st, false, sizeof st);
res = 0;
dfs(x, y, 1);
cout << res << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T --) {
solve();
}
// solve();
return 0;
}
- 在求方案时,需要回溯,要进行恢复现场这个操作