补全9月11日至13日课评:为13名学生创建请假文档,为5个班级创建总结文档
This commit is contained in:
72
C++代码/学习/走出迷宫的最短路径.cpp
Normal file
72
C++代码/学习/走出迷宫的最短路径.cpp
Normal file
@@ -0,0 +1,72 @@
|
||||
#include <bits/stdc++.h>
|
||||
#define endl '\n'
|
||||
using namespace std;
|
||||
|
||||
int n, m, z; // z表示当前走了多少个节点
|
||||
int arr[160][160];
|
||||
int s1, s2, e1, e2;
|
||||
|
||||
int fx[] = {0, 0, 1, 0, -1};
|
||||
int fy[] = {0, 1, 0, -1, 0};
|
||||
|
||||
int q[40000][3]; // 下标0表示前上一个点
|
||||
|
||||
void print(int k){
|
||||
if(k == 0) return ;
|
||||
print(q[k][0]); // 先走回到最前面的位置
|
||||
cout << "(" << q[k][1] << "," << q[k][2] << ")";
|
||||
if(k != z) cout << "->";
|
||||
}
|
||||
|
||||
void bfs(int x, int y){
|
||||
q[1][0] = 0;
|
||||
q[1][1] = x;
|
||||
q[1][2] = y;
|
||||
arr[x][y] = 1;
|
||||
int head = 1, tail = 1;
|
||||
|
||||
while(head <= tail){
|
||||
int cx = q[head][1];
|
||||
int cy = q[head][2];
|
||||
|
||||
int tx, ty;
|
||||
for(int i = 1; i <= 4; i++){
|
||||
tx = cx + fx[i];
|
||||
ty = cy + fy[i];
|
||||
|
||||
if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && arr[tx][ty] == 0){
|
||||
tail++;
|
||||
|
||||
q[tail][0] = head;
|
||||
q[tail][1] = tx;
|
||||
q[tail][2] = ty;
|
||||
|
||||
if(tx == e1 && ty == e2){
|
||||
z = tail;
|
||||
print(tail);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
arr[tx][ty] = 1;
|
||||
}
|
||||
}
|
||||
head++;
|
||||
}
|
||||
}
|
||||
|
||||
int main(){
|
||||
cin >> n >> m;
|
||||
for(int i = 1; i <= n; i++){
|
||||
for(int j = 1; j <= m; j++){
|
||||
cin >> arr[i][j];
|
||||
}
|
||||
}
|
||||
cin >> s1 >> s2 >> e1 >> e2;
|
||||
|
||||
bfs(s1, s2);
|
||||
|
||||
cout << "no way";
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user