You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <iostream>
using namespace std;
int dfs(int i, int j, int visited[][10], int cnt, int m, int n) {
// 终止条件当遍历到最后一个格子时如果已经遍历了mn个格子则符合条件数量加1
if (i == m && j == n) {
if (cnt == m * n)
return 1;
else
return 0;
}
// 非终止条件,继续递归
int res = 0;
if (i > 1 and !visited[i - 2][j - 1]) {
visited[i - 2][j - 1] = 1;
res += dfs(i - 1, j, visited, cnt + 1, m, n);
visited[i - 2][j - 1] = 0;
}
if (j > 1 and !visited[i - 1][j - 2]) {
visited[i - 1][j - 2] = 1;
res += dfs(i, j - 1, visited, cnt + 1, m, n);
visited[i - 1][j - 2] = 0;
}
if (i < m and !visited[i][j - 1]) {
visited[i][j - 1] = 1;
res += dfs(i + 1, j, visited, cnt + 1, m, n);
visited[i][j - 1] = 0;
}
if (j < n and !visited[i - 1][j]) {
visited[i - 1][j] = 1;
res += dfs(i, j + 1, visited, cnt + 1, m, n);
visited[i - 1][j] = 0;
}
return res;
}
int main() {
int m, n;
cin >> m >> n;
int visited[m][10] = {0}; // 二维数组表示已经遍历的格子
visited[0][0] = 1;
int cnt = 1; // 已经遍历的格子数目
cout << dfs(1, 1, visited, cnt, m, n) << endl;
return 0;
}