洛谷 P1443 馬的遍歷題解

題目連接:https://www.luogu.org/problem/P1443html

題目描述

有一個n*m的棋盤(1<n,m<=400),在某個點上有一個馬,要求你計算出馬到達棋盤上任意一個點最少要走幾步ios

輸入格式

一行四個數據,棋盤的大小和馬的座標數組

輸出格式

一個n*m的矩陣,表明馬到達某個點最少要走幾步(左對齊,寬5格,不能到達則輸出-1)spa

輸入輸出樣例

輸入 #1
3 3 1 1
輸出 #1
0    3    2    
3    -1   1    
2    1    4    

題解

此題是典型的BFS問題。不過和01迷宮問題有兩點不一樣:一是馬的走法不是上下左右,因此pos數組須要修改,二是走的步數須要從隊列中元素的步數加1。還有一個小問題就是要控制cout的輸出格式,剛開始沒有注意,10個全WA了。code

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <math.h>
 4 #include <algorithm>
 5 #include <string.h>
 6 
 7 using namespace std;
 8 
 9 struct Node
10 {
11     int x, y;
12     int step;
13 };
14 Node q[100005];
15 
16 const int MAXN = 1005;
17 int n, m, a, b, c, d, step, front, rear, ans[MAXN][MAXN]; 
18 int pos[8][2] = {2, 1, 2, -1, 1, 2, 1, -2, -1, 2, -1, -2, -2, 1, -2, -1};
19 bool vis[MAXN][MAXN];
20 
21 void bfs()
22 {
23     Node now, next;
24     now.x = a;
25     now.y = b;
26     vis[a][b] = 1; 
27     now.step = 0;
28     front = rear = 0;
29     q[rear] = now;
30     rear++;
31     while(front < rear)
32     {
33         now = q[front++];
34         for(int i = 0; i < 8; i++)
35         {
36             int nx = now.x + pos[i][0]; 
37             int ny = now.y + pos[i][1]; 
38             if(nx <= n && nx > 0 && ny <= m && ny > 0 
39                 && vis[nx][ny] == false) 
40             {
41                 vis[nx][ny] = true;
42                 q[rear].x = nx;
43                 q[rear].y = ny;
44                 q[rear].step = now.step + 1;
45                 ans[nx][ny] = q[rear].step;
46                 rear++;
47             }
48         } 
49     }
50 }
51 
52 int main()
53 {
54     cin >> n >> m >> a >> b;
55     for(int i = 1; i <= n; i++)
56     {
57         for(int j = 1; j <= m; j++)
58         {
59             ans[i][j] = -1;
60         }
61     }
62     ans[a][b] = 0;
63     step = 1;
64     bfs();
65     for(int i = 1; i <= n; i++)
66     {
67         for(int j = 1; j <= m; j++)
68         {
69             cout.width(5);
70             cout.setf(ios::left);
71             cout << ans[i][j];
72         }
73         cout << endl;
74     }
75     return 0;
76 }
相關文章
相關標籤/搜索