-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.cpp
54 lines (51 loc) · 1.53 KB
/
code.cpp
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
#include <bits/stdc++.h>
using namespace std;
void solution(vector<vector<int>> &maze, int sx, int sy, int ex, int ey, vector < pair<int, int>> &path, vector < pair<int, int>> &best) {
if (sx == ex && sy == ey) {
path.push_back({ sx,sy });
if (best.empty() || best.size() > path.size()) {
best = path;
}
path.pop_back();
return;
}
path.push_back({ sx ,sy });
maze[sx][sy] = 1;
if (sx > 0 && maze[sx - 1][sy] == 0) {//可以向左移动 // go left
solution(maze, sx - 1, sy, ex, ey, path, best);
}
if (sx < maze.size() - 1 && maze[sx + 1][sy] == 0) {//可以向右移动 // go right
solution(maze, sx + 1, sy, ex, ey, path, best);
}
if (sy > 0 && maze[sx][sy - 1] == 0) {//可以向上移动 // go up
solution(maze, sx, sy - 1, ex, ey, path, best);
}
if (sy < maze[0].size() - 1 && maze[sx][sy + 1] == 0) {//可以向下移动 // go down
solution(maze, sx, sy + 1, ex, ey, path, best);
}
path.pop_back();
maze[sx][sy] = 0;
}
int HuaWei_maze(void) {
int N, M;
cin >> N >> M;
vector<vector<int>> maze(N, vector<int>(M));
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
cin >> maze[i][j];
int x1, y1, x2, y2;
while (cin >> x1 >> y1 >> x2 >> y2) {
vector<pair<int, int>> temp, dir;
solution(maze, x1, y1, x2, y2, temp, dir);
if (dir.empty()) {
cout << "cannot reach" << endl;
continue;
}
cout << "distance of best path: " << dir.size() - 1 << endl;
cout << "best path: " << endl;
for (auto i : dir)
cout << '(' << i.first << ',' << i.second << ')' << endl;
cout << endl;
}
return 0;
}