洛谷马的遍历

题目链接:https://www.luogu.com.cn/problem/P1443

马走日字象走田,究竟怎么走呢?

画画图就明白啦,

除此之外,这个题就是一道稍微变形的bfs题目,需要注意的是,左对齐输出一定要有,否则你即使是运行结果对了也怎么都是WA,别问,说多了都是泪

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m,sx,sy;
 4 int dis[410][410];
 5 int dir[8][2]={
 6     {-2,-1},
 7     {-2,1},
 8     {-1,2},
 9     {1,2},
10     {2,1},
11     {2,-1},
12     {1,-2},
13     {-1,-2} 
14 };//为什么这样设座标请看上图 
15 struct node
16 {
17     int x;
18     int y;
19 };
20 #define CHECK(x,y)(x>=1&&x<=n&&y>=1&&y<=m)//边界条件改为1了,因为马走日子 
21 void bfs(int x,int y)
22 {
23     dis[x][y]=0; //标记走过 
24     queue<node>q;
25     node start,next;
26     start.x=x;
27     start.y=y;
28     q.push(start);
29     while(!q.empty())
30     {
31         start=q.front();
32         q.pop();
33         for(register int i=0;i<8;i++)
34         {
35             next.x=start.x+dir[i][0];
36             next.y=start.y+dir[i][1];
37             if(CHECK(next.x,next.y)&&dis[next.x][next.y]==-1)
38             {
39                 dis[next.x][next.y]=0;//标记 
40                 dis[next.x][next.y]=dis[start.x][start.y]+1;//下一个方位,步数是父节点+1 
41                 q.push(next);//下一个 
42             }
43         }
44     }
45 }
46 int main()
47 {
48     ios::sync_with_stdio(false);
49     cin>>n>>m>>sx>>sy;
50     for(register int i=1;i<=n;i++)
51         for(register int j=1;j<=m;j++)
52             dis[i][j]=-1;//先将所以元素都覆盖为-1 
53     bfs(sx,sy);//bfs 
54     for(register int i=1;i<=n;i++)
55     {
56         for(register int j=1;j<=m;j++)
57         {
58             cout<<left<<setw(5)<<dis[i][j];//左对齐输出场宽为5 
59         }
60         cout<<endl;
61     }
62     
63     return 0;
64 }

这里提供一下bfs和dfs的一些相关小知识:

bfs模板:

 1 int dir[4][2]= {0,1,0,-1,1,0,-1,0}; // 方向向量
 2 struct State // BFS 队列中的状态数据结构
 3 {
 4     int x,y; // 坐标位置
 5     int Step_Counter; // 搜索步数统计器
 6 };
 7 State a[maxn];
 8 
 9 bool CheckState(State s) // 约束条件检验
10 {
11     if(!used[s.x][s.y] && ...) // 边界或未被标记
12         return true;
13     else // 约束条件冲突
14         return false;
15 }
16 
17 void bfs(State st)
18 {
19     queue <State> q; // BFS 队列
20     State now,next; // 定义2 个状态,当前和下一个
21     q.push(st); // 入队
22     used[st.x][st.y]=false; // 访问标记
23     while(!q.empty())//当队列不为空时
24     {
25         now=q.front(); // 取队首元素进行扩展
26         if(now==G) //
27         {
28             ...... // 做相关处理
29             return;
30         }
31         for(int i=0; i<4; i++)
32         {
33             next.x=now.x+dir[i][0]; // 按照规则生成下一个状态
34             next.y=now.y+dir[i][1];
35             if(CheckState(next)) // 如果状态满足约束条件则入队
36             {
37                 q.push(next);//入队
38                 used[next.x][next.y]=false; //访问标记
39             }
40         }
41         q.pop(); // 队首元素出队
42     }
43 }

 

posted @ 2022-03-19 18:37  江上舟摇  阅读(30)  评论(0编辑  收藏  举报