标签:bfs
BFS稍微改变了一下,走的步法不一样了。
AC代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 10;
int vis[maxn][maxn];
int dis[maxn][maxn];
int x0,y0,x1,y1;
int dr[8][2] ={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
int ans;
struct node{
int x,y;
};
node p[maxn][maxn];
void print_road(node u);
void bfs(){
node init,next;
queue<node> q;
init.x = x0;init.y = y0;
q.push(init);
dis[x0][y0] = 0;
vis[x0][y0] = 1;
while(!q.empty()){
next = q.front();q.pop();
if(next.x == x1 && next.y == y1) {ans = dis[next.x][next.y];return;}
for(int i=0;i<8;i++){
int dx = next.x + dr[i][0];
int dy = next.y + dr[i][1];
if(dx < 1 || dx > 8 || dy < 1 || dy > 8 || vis[dx][dy]) continue;
init.x = dx; init.y = dy; q.push(init);
vis[dx][dy] = 1;dis[dx][dy] = dis[next.x][next.y]+1;p[dx][dy] = next;
}
}
ans = -1;
}
int main(){
string s,t;
while(cin>>s){
memset(vis,0,sizeof(vis));
memset(dis,0,sizeof(dis));
cin >> t;
y0 = s[0] - ‘a‘ + 1;
x0 = s[1] - ‘0‘;
y1 = t[0] - ‘a‘ + 1;
x1 = t[1] - ‘0‘;
bfs();
if(ans == -1) cout<<"No Solution!"<<endl;
else
cout<<"To get from "<<s<<" to "<<t<<" takes "<<ans<<" knight moves."<<endl;
}
return 0;
}
作为练习,我还写了一个打印路程的函数。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 10;
int vis[maxn][maxn];
int dis[maxn][maxn];
int x0,y0,x1,y1;
int dr[8][2] ={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
int ans;
struct node{
int x,y;
};
node p[maxn][maxn];
void print_road(node u);
void bfs(){
node init,next;
queue<node> q;
init.x = x0;init.y = y0;
q.push(init);
dis[x0][y0] = 0;
vis[x0][y0] = 1;
while(!q.empty()){
next = q.front();q.pop();
if(next.x == x1 && next.y == y1) {ans = dis[next.x][next.y];print_road(next);return;}
for(int i=0;i<8;i++){
int dx = next.x + dr[i][0];
int dy = next.y + dr[i][1];
if(dx < 1 || dx > 8 || dy < 1 || dy > 8 || vis[dx][dy]) continue;
init.x = dx; init.y = dy; q.push(init);
vis[dx][dy] = 1;dis[dx][dy] = dis[next.x][next.y]+1;p[dx][dy] = next;
}
}
ans = -1;
}
void print_road(node u){
vector<node> v;
for(;;){
v.push_back(u);
if(u.x == x0 && u.y == y0) break;
u = p[u.x][u.y];
}
for(int i = v.size()-1;i>=0;i--){
printf("(%d,%c)",v[i].x,‘a‘+v[i].y-1);
}
printf("\n");
}
int main(){
int T;
cin >> T;
string s,t;
while(T--){
memset(vis,0,sizeof(vis));
memset(dis,0,sizeof(dis));
cin >> s >> t;
y0 = s[0] - ‘a‘ + 1;
x0 = s[1] - ‘0‘;
y1 = t[0] - ‘a‘ + 1;
x1 = t[1] - ‘0‘;
bfs();
if(ans == -1) cout<<"No Solution!"<<endl;
else cout<<ans<<endl;
}
return 0;
}
标签:bfs
原文地址:http://blog.csdn.net/iboxty/article/details/45935453