Difficulty: popularity/improvement-
Title Type: BFS
Number of submissions: 5
Related knowledge: BFS
Title Description
There is a n*m board (1<n,m<=200), at some point there is a horse that asks you to calculate the minimum number of steps you need to take to get to any point on the board.
Input/output format
Input format:
A row of four data, the size of the chessboard and the coordinates of the horse
Output format:
A n*m matrix that represents the minimum number of steps a horse must take to reach a point (left-aligned, 5-wide, not reachable-1)
Code:
#include <iostream>#include<queue>#include<cstring>#include<cstdio>using namespacestd;intN, M, SX, SY;intd[2][8] = {{1,1, -1, -1,2,2, -2, -2}, {2, -2,2, -2,1, -1,1, -1}};inta[2001][2001];intvisited[2001][2001];structpos{intx, y, step; POS (intXxintYyints): X (xx), Y (yy), step (s) {}};BOOLCheckintXinty) { if(x>=1&&x<=n&&y>=1&&y<=m&&visited[x][y]==-1) return true; return false;} Queue<pos>Q;intMain () {CIN>>n>>m>>sx>>Sy; Memset (visited,-1,sizeof(visited)); intI, J; Q.push (POS (SX, SY,0)); Visited[sx][sy]=0; while(!Q.empty ()) {POS P=Q.front (); for(i =0; I <8; i++){ if(Check (p.x+d[0][i], p.y+d[1][i]) {Q.push (pos (p.x+d[0][i], p.y+d[1][i], p.step+1)); visited[p.x +d[0][i]] [P.y+d[1][i]] = p.step+1; }} q.pop (); } for(i =1; I <= N; i++){ for(j =1; J <= M; J + +) printf ("%-5d", Visited[i][j]); cout<<Endl; } return 0;}
Note:
The Naked bfs water problem. But I've been stuck for a while. Originally to simplify the code with the direction of the array, the result visited added to the pop before the cycle, and then a variety of timeouts, think for a long time also did not want to understand. But the magic is when I first started to send to the teacher, saw visited that line, found not quite right. Should be added to the queue when the mark Ah. Otherwise it will expand to its own, no problem to blame it. Here BFS is over, punch in!
1443 the traverse of the horse