题目链接:点我啊╭(╯^╰)╮
题目大意:
从 ( 1 , 1 ) (1,1) (1,1)走到 ( 5 , 5 ) (5,5) (5,5)求最短路径并输出
解题思路:
无
代码思路:
无
核心:用一道简单题记录一下模板
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
int dx[]= {1,-1,0,0};
int dy[]= {0,0,1,-1};
int cnt, mp[10][10];
bool vis[10][10];
stack <pii> r;
struct pot {
int u, v;
pot *pre;
};
void BFS(int u, int v) {
queue <pot> Q;
pot q, n, n_cnt[700];
q.u = u, q.v = v;
q.pre = NULL;
Q.push(q);
vis[u][v] = true;
while(!Q.empty()) {
q = Q.front();
Q.pop();
for(int i=0; i<=4; i++) {
n.u=q.u+dx[i];
n.v=q.v+dy[i];
if(n.u<1 || n.u>5 || n.v<1 || n.v>5) continue;
if(vis[n.u][n.v] || mp[n.u][n.v]) continue;
//cout<<n.u<<" "<<n.v<<endl;
vis[n.u][n.v] = true;
n_cnt[cnt] = q;
n.pre = &n_cnt[cnt++]; //这里一开始弄错了、没连起来....
if(n.u==5 && n.v==5) {
while(n.pre) {
r.push(make_pair(n.u, n.v));
n = *n.pre;
}
r.push(make_pair(1, 1));
return;
}
Q.push(n);
}
}
}
void print() {
while(!r.empty()) {
printf("(%d, %d)\n", r.top().first-1, r.top().second-1);
r.pop();
}
}
int main() {
for(int i=1; i<6; i++)
for(int j=1; j<6; j++)
scanf("%d", &mp[i][j]);
BFS(1, 1);
print();
}