1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <bits/stdc++.h>
using namespace std;
#define MP(x, y) make_pair(x, y)
typedef pair<int, int> PII;
const int N = 25;
int n, ans; char g[N][N];
string str;
map<string, vector<PII> > _map;
void dfs(int x, int y, int s) { if (s == n) { _map[str].push_back(MP(x, y)); return; } if (x + 1 <= n) { str = str + g[x + 1][y]; dfs(x + 1, y, s + 1); str.erase(str.end() - 1); } if (y + 1 <= n) { str = str + g[x][y + 1]; dfs(x, y + 1, s + 1); str.erase(str.end() - 1); } }
void dfs1(int x, int y, int s) { if (s == n) { if (_map.find(str) != _map.end()) { vector<PII> list = _map[str]; for (int i = 0; i < list.size(); i++) { if (x == list[i].first && y == list[i].second) { ans++; _map.erase(str); break; } } } return; } if (x - 1 >= 0) { str = str + g[x - 1][y]; dfs1(x - 1, y, s + 1); str.erase(str.end() - 1); } if (y - 1 >= 0) { str = str + g[x][y - 1]; dfs1(x, y - 1, s + 1); str.erase(str.end() - 1); } }
int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> g[i] + 1; str = str + g[1][1]; dfs(1, 1, 1); str = ""; str = str + g[n][n]; dfs1(n, n, 1); cout << ans << endl; return 0; }
|