Los traversal solution to a problem Valley P1443 horse

Topic links: https://www.luogu.org/problem/P1443

Title Description

N * m has a board (1 <n, m <= 400), there is a horse at some point, requires you to go happened in arbitrary point on the board reaches a short run for

Input Format

A row of four coordinate data, the size of the board and horse

Output Format

A matrix of n * m, horse reaches a point representative of a minimum of steps to go (left, 5 wide grid, the output does not reach -1)

Sample input and output

Input # 1
3 3 1 1
Output # 1
0    3    2    
3    -1   1    
2    1    4    

answer

This problem is typical of BFS problem. But and 01 mazes in two ways: First, the horse and the walk is not up and down, so you need to modify the array pos, the second is the need to increase the number of steps walked a few steps from the queue element 1. There is also a small problem is to control the output format cout, the beginning did not pay attention, the 10 full-WA.

 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 }

 

Guess you like

Origin www.cnblogs.com/zealsoft/p/11330835.html