P1747 好奇怪的游戏(洛谷)

题目描述:

  传送门

思路:

  一个很常见的bfs问题,关键是如何处理搜索走马位置和走象的位置。对于处于某一个坐标时,我们需要考虑的是当前位置的下一个可能的位置在哪,然后搜索出合理的位置再将其入队,再从而去进入到下一个位置去搜索。所以如何搜某一位置的下一个位置:对于走马方式,有8个方向,则一般有8个位置可走(注意:前提是在边界内);对于走象,有4个位置可走;因此每个位置走到下一步时,我们需要检测12个位置里面合理的位置并将其入队即可。直到搜索到目标位置。

实现代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int mapp[100][100];
 5 typedef struct node{
 6     int x;
 7     int y;
 8     int step;        //记录当前点到原点距离 
 9 }P;
10 int x;
11 int y;            //白黑马的坐标 
12 int x2;
13 int y2;
14 int dx[2]={-1,1};
15 int dy[2]={-1,1};
16 
17 int bfs(int sx,int sy){        //起点横纵坐标
18     memset(mapp,0,sizeof(mapp));
19     P st;
20     st.x=sx,st.y=sy,st.step=0;
21     queue<P> que;
22     que.push(st);
23     mapp[st.x][st.y]=1;        //代表访问过 
24     
25     while(!que.empty()){
26         P cur=que.front();        //队头元素取出 
27         que.pop();
28         if(cur.x==1&&cur.y==1){        //处于(1,1)位置 
29             return cur.step;
30         }
31             
32         for(int i=0;i<2;i++){        //先走田 
33             for(int j=0;j<2;j++){
34                 int xx=cur.x+2*dx[i];
35                 int yy=cur.y+2*dy[j];
36                 if(xx>=1&&yy>=1){
37                     if(mapp[xx][yy]) continue;
38                     P temp;
39                     temp.x=xx;
40                     temp.y=yy;
41                     temp.step=cur.step+1;
42                     que.push(temp);
43                     mapp[xx][yy]=1;        //访问过 
44                 }
45             }
46         }
47         
48         for(int i=0;i<2;i++){        //走日 
49             for(int j=0;j<2;j++){
50                 int xx=cur.x+2*dx[i];
51                 int yy=cur.y+dy[j];
52                 if(xx>=1&&yy>=1){
53                     if(mapp[xx][yy])    continue;
54                     P temp;
55                     temp.x=xx;
56                     temp.y=yy;
57                     temp.step=cur.step+1;
58                     que.push(temp);
59                     mapp[xx][yy]=1;        //访问过 
60                 }
61                 
62                 xx=cur.x+dx[i];
63                 yy=cur.y+2*dy[j];
64                 if(xx>=1&&yy>=1){
65                     if(mapp[xx][yy])    continue;
66                     P temp;
67                     temp.x=xx;
68                     temp.y=yy;
69                     temp.step=cur.step+1;
70                     que.push(temp);
71                     mapp[xx][yy]=1;        //访问过 
72                 }
73             }
74         }
75     }
76     return 0;
77 }
78 int main(){
79     cin>>x>>y;
80     cin>>x2>>y2;
81     
82     cout<<bfs(x,y)<<endl;
83     cout<<bfs(x2,y2); 
84     return 0;
85 }

猜你喜欢

转载自www.cnblogs.com/xwh-blogs/p/12735505.html