对称迷宫
2020-07-01 21:26:27
本文总阅读量

题目描述

用EXCEL求解迷宫真香~

wlxsq有一个的网格迷宫,每一个网格都有一个字母编号。

他要从左上角出发,走到右下角,由于wlxsq很懒,所以他每次只会往右或者往下走一格。

由于最后到终点的路径方案太多太多了,所以wlxsq想让你计算出所有不同的对称的路径个数。

例如:

1
2
3
ABA
BBB
ABA

对称路径6条:有ABABA(2条)、ABBBA(4条)

不同的对称路径有: 有ABABA、ABBBA

输入

第一行输入一个数,表示迷宫的大小。

接下来输入的字母迷宫

输出

输出对称路径的数量

样例

输入

1
2
3
4
3
ABA
BBB
ABA

输出

1
2

提示

【评测用例规模与约定】

对于的数据,

对于的数据,

题解

双向DFS。

代码

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;
}