Subject to the effect
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 does not reach the Output - . 1 )
Sample input and output
Input # 1
3 3 1 1
Output # 1
0 3 2 3 -1 1 2 1 4
Thinking
Wide search + STL queue using the structure variable Pos stored coordinates using two-dimensional array of the Map [ 401 ] [ 401 ] memory map (answer) using constant array dx [] dy [] storage horses can go eight directions using the type of queue Pos maintenance value of the coordinate point
Code
#include <Queue> #include <CString> #include <cstdio> the using namespace STD; struct Pos // structure variables Pos, horse store x, y coordinate values { int x, y; }; Queue <Pos> Q; // definition of a type Pos queue Q int n-, m, TX, TY, MP [ 401 ] [ 401 ], X, Y; const int DX [] {= - . 1 , - . 1 , - 2 , - 2 , . 1 , . 1 , 2 , 2 }; const int Dy [] = {-2 , 2 - 1 , 1 - 2 , 2 - 1 , 1 }; // 8 directions horse void BFS ( int SX, int SY) { q.push ((Pos) {SX, SY}) ; // insertion process values MP [SX] [SY] = 0 ; the while (! q.empty ()) { X = q.front () X;. Y = q.front () Y;. q.pop (); for ( int I = 0 ; I < . 8;i++) { tx=x+dx[i]; ty=y+dy[i]; if(tx<=0||tx>n||ty<=0||ty>m) continue; if(mp[tx][ty]!=-1) continue; mp[tx][ty]=mp[x][y]+1; q.push((Pos){tx,ty}); } } } int main() { memset(mp,-1,sizeof(mp)); int sx,sy; scanf("%d %d %d %d",&n,&m,&sx,&sy); bfs(sx,sy); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) printf("%-5d",mp[i][j]); //注意输出格式 printf("\n"); } return 0; }
The title difficulty popularity / awareness -