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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
| #include <bits/stdc++.h>
using namespace std;
int maps[58][58] = {{1,0,1}};
int visited[60][60] = {0};
struct point {
int x;
int y;
int step;
vector<pair<int, int>> path;
};
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
queue<point> r;
string path1 = "S";
int main() {
int n = 56, m = 56;
int startx = 1, starty = 1;
int endx = 15, endy = 32;
if (maps[startx][starty] != 0) {
printf("起始点不可通行!起始点值:%d\n", maps[startx][starty]);
return 0;
}
if (maps[endx][endy] != 0) {
printf("终点不可通行!终点值:%d\n", maps[endx][endy]);
return 0;
}
printf("起始点:(%d,%d),终点:(%d,%d)\n", startx, starty, endx, endy);
point p;
p.x = startx;
p.y = starty;
p.step = 0;
visited[startx][starty] = 1;
r.push(p);
while (!r.empty()) {
point current = r.front();
int x = r.front().x, y = r.front().y;
if (x == endx && y == endy) {
printf("到达终点,共%d步\n", r.front().step);
for (int i = 0; i < current.path.size(); i++) {
printf("第%d步: (%d, %d)", i+1, current.path[i].first, current.path[i].second);
if (i > 0) {
int dx = current.path[i].first - current.path[i-1].first;
int dy = current.path[i].second - current.path[i-1].second;
if (dx == -1) printf(" [从(%d,%d)向上移动]", current.path[i-1].first, current.path[i-1].second), path1 += "W";
else if (dx == 1) printf(" [从(%d,%d)向下移动]", current.path[i-1].first, current.path[i-1].second), path1 += "S";
else if (dy == -1) printf(" [从(%d,%d)向左移动]", current.path[i-1].first, current.path[i-1].second), path1 += "A";
else if (dy == 1) printf(" [从(%d,%d)向右移动]", current.path[i-1].first, current.path[i-1].second), path1 += "D";
}
printf("\n");
}
std::cout << "结果为:" << path1 << '\n';
return 0;
}
for (int j = 0; j < 4; j++) {
int tx = x + dx[j];
int ty = y + dy[j];
if (tx >= 0 && ty >= 0 && tx < n && ty < m &&
maps[tx][ty] == 0 && visited[tx][ty] == 0) {
point temp;
temp.x = tx;
temp.y = ty;
temp.step = current.step + 1;
temp.path = current.path;
temp.path.push_back({tx, ty});
r.push(temp);
visited[tx][ty] = 1;
}
}
r.pop();
}
puts("未找到结果!");
return 0;
}
|