BFS简单搜索--POJ 2243
生活随笔
收集整理的這篇文章主要介紹了
BFS简单搜索--POJ 2243
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
這題就是簡單的BFS搜索,剛剛轉(zhuǎn)到C++,還有很多庫函數(shù)不熟悉,理解到BFS是一種奇妙的迭代法,其用的主要是隊列的性質(zhì)。
1 /*BFS簡單搜索*/2 #include<iostream>
3 #include<queue>
4 #include<cstring>
5
6 using namespace std;
7
8 int map[8][8];//標記數(shù)組
9 int dir[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};
10
11 struct point
12 {
13 int row,col;
14 int step;
15 }p;
16
17 int bfs(point s,point e,int step)
18 {
19 queue<point> que;
20 point p;
21 int i,x=0,y=0;
22 while(1)
23 {
24 if(s.row==e.row&&s.col==e.col)//對于s的這樣使用很不錯
25 {
26 return s.step;
27 }
28 for(i=0;i<8;i++)
29 {
30 x=s.row+dir[i][0];
31 y=s.col+dir[i][1];
32 if(x<0||x>=8||y<0||y>=8)
33 continue;
34 if(!map[x][y])
35 {
36 p.row=x;
37 p.col=y;
38 map[x][y]=1;
39 p.step=s.step+1;//注意計算步數(shù)
40 que.push(p);
41 }
42 }
43 s=que.front();
44 que.pop();
45 }
46 }
47 int main()
48 {
49 point start,end;
50 char c1[3],c2[3];
51 while(cin>>c1>>c2)
52 {
53 start.col=c1[0]-'a';
54 end.col=c2[0]-'a';
55 start.row=c1[1]-'1';
56 end.row=c2[1]-'1';
57 start.step=0;
58 memset(map,0,sizeof(map));
59 cout<<"To get from "<<c1<<" to "<<c2<<" takes "<<bfs(start,end,0)<<" knight moves."<<endl;
60 }
61 return 0;
62 }
轉(zhuǎn)載于:https://www.cnblogs.com/hankers/archive/2012/02/16/2355098.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的BFS简单搜索--POJ 2243的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用swift集成移动广告聚合平台
- 下一篇: CSU 1259 bfs找最短路