poj 2243 bfs 利用 结构体中的step成员保存步数 ,STL的队列
2014-08-09 10:19
357 查看
//BFS #include <iostream> #include <queue> using namespace std; bool used[8][8]; int move[8][2]={1,2, -1,2, -2,1, -2,-1, -1,-2, 1,-2, 2,-1, 2,1}; struct position { int i,j; int step; position(int a,int b,int c) { i=a; j=b; step=c; } }; int main() { char a[2],b[2]; int bi,bj,ei,ej,i; while (cin>>a>>b) { bi=a[0]-'a'; bj=a[1]-'1'; ei=b[0]-'a'; ej=b[1]-'1'; memset(used,false,sizeof(used)); queue<position> myqueue; position temp(bi,bj,0),now(0,0,0); myqueue.push(temp); used[bi][bj]=true; while (myqueue.empty()==false) { temp=myqueue.front(); myqueue.pop(); if (temp.i==ei && temp.j==ej) break; for (i=0;i<8;i++) { now.i=temp.i+move[i][0]; now.j=temp.j+move[i][1]; if (now.i>=0 && now.i<8 && now.j>=0 && now.j<8 && used[now.i][now.j]==false) { now.step=temp.step+1; used[now.i][now.j]=true; myqueue.push(now); } } } cout<<"To get from "<<a<<" to "<<b<<" takes "<<temp.step<<" knight moves."<<endl; } return 0; }
//BFS
#include <iostream>
#include <queue>
using namespace std;
bool used[8][8];
int move[8][2]={1,2, -1,2, -2,1, -2,-1, -1,-2, 1,-2, 2,-1, 2,1};
struct position
{
int i,j;
int step;
};
int main()
{
char a[2],b[2];
int bi,bj,ei,ej,i;
while (cin>>a>>b)
{
bi=a[0]-'a';
bj=a[1]-'1';
ei=b[0]-'a';
ej=b[1]-'1';
memset(used,false,sizeof(used));
queue<position> myqueue;
struct position temp,now;
temp.i=bi; temp.j=bj; temp.step=0;
now.i=0; now.j=0; now.step=0;
myqueue.push(temp);
used[bi][bj]=true;
while (myqueue.empty()==false)
{
temp=myqueue.front();
myqueue.pop();
if (temp.i==ei && temp.j==ej)
break;
for (i=0;i<8;i++)
{
now.i=temp.i+move[i][0];
now.j=temp.j+move[i][1];
if (now.i>=0 && now.i<8 && now.j>=0 && now.j<8 && used[now.i][now.j]==false)
{
now.step=temp.step+1;
used[now.i][now.j]=true;
myqueue.push(now);
}
}
}
cout<<"To get from "<<a<<" to "<<b<<" takes "<<temp.step<<" knight moves."<<endl;
}
return 0;
}
相关文章推荐
- C++利用stl::sort对结构体数组中的字符串成员排序
- POJ 2243 ZOJ 1091 UVaOJ 439 Knight moves(BFS广度优先搜索)
- POJ 3278 用队列实现BFS搜索
- BFS简单搜索--POJ 2243
- poj 2243 双向bfs和A*
- STL有限队列的灵活运用+IO优化+区间最大最小——POJ Sliding Window
- 如何在 Visual C++ 中使用 STL 队列类的该成员函数
- POJ 2243 bfs
- poj 2243 bfs Knight Moves
- poj 3984 BFS+DFS(保存路径)
- poj 2243 Knight Moves bfs
- POJ 3126 Prime Path 第一道BFS 循环队列,AC的很辛苦!
- ZOJ 2165题解此题不算难可是有一些细节需注意,很容易出错。总归就是BFS加队列,用STL实现较方便
- POJ 3278第一道BFS,此题刚开始做是纠结了很久,毕竟是第一道要用到队列又赶紧把队列看了一遍,经过几次WA后左后总算AC了
- POJ 2243 BFS 和 简单的调试方法学习
- poj 2243 bfs
- BFS解决POJ 2243
- 关于stl::vector中存储带指针类型成员的结构体指针
- 【bfs优先队列】POJ 2312
- poj 2243 -- Knight Moves (bfs)