码迷,mamicode.com
首页 > 其他好文 > 详细

poj1915 Knight Moves(BFS)

时间:2017-11-15 22:05:28      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:str   struct   过多   main   std   span   amp   eps   bfs   

题目链接

http://poj.org/problem?id=1915

题意

输入正方形棋盘的边长、起点和终点的位置,给定棋子的走法,输出最少经过多少步可以从起点走到终点。

思路

经典bfs题目。

代码

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 using namespace std;
 6 
 7 struct Node
 8 {
 9     int r;
10     int c;
11     int steps;
12 
13     Node(int r, int c, int steps):r(r), c(c), steps(steps){}
14 };
15 
16 const int N = 310;
17 queue<Node> q;
18 int dir[8][2]={ {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, -2}, {2, -1}, {2, 1}, {1, 2} };
19 int n;
20 int sr, sc;
21 int er, ec;
22 int visit[N][N];
23 
24 void bfs()
25 {
26     while(!q.empty())
27     {
28         Node node = q.front();
29         q.pop();
30         if(node.r==er && node.c==ec)
31         {
32             cout<<node.steps<<endl;
33             return;
34         }
35         for(int i=0; i<8; i++)
36         {
37             int nr = node.r + dir[i][0];
38             int nc = node.c + dir[i][1];
39             if(nr>=0 && nr<n && nc>=0 && nc<n && !visit[nr][nc])
40             {
41                 visit[nr][nc] = 1;
42                 q.push(Node(nr, nc, node.steps+1));
43             }
44         }
45     }
46 }
47 
48 int main()
49 {
50     //freopen("poj1915.txt", "r", stdin);
51     int t;
52     cin>>t;
53     while(t--)
54     {
55         cin>>n;
56         cin>>sr>>sc;
57         cin>>er>>ec;
58 
59         memset(visit, 0, sizeof(visit));
60         while(!q.empty()) q.pop();
61         visit[sr][sc] = 1;
62         q.push(Node(sr, sc, 0));
63         bfs();
64     }
65     return 0;
66 }

poj1915 Knight Moves(BFS)

标签:str   struct   过多   main   std   span   amp   eps   bfs   

原文地址:http://www.cnblogs.com/sench/p/7840663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!