1. 程式人生 > >P1443 馬的遍歷

P1443 馬的遍歷

right 輸出格式 logs lba -s startx 坐標 urn 輸入

P1443 馬的遍歷

題目描述

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

輸入輸出格式

輸入格式:

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

輸出格式:

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

輸入輸出樣例

輸入樣例#1:
3 3 1 1
輸出樣例#1:
0    3    2    
3    -1   1    
2    1    4    
#include<iostream>
#include<cstdio>
#include
<cmath> #include<algorithm> #include<queue> using namespace std; const int N=401; const int xd[]={-1,-2,-2,-1,1,2,2,1}; const int yd[]={-2,-1,1,2,2,1,-1,-2}; struct node{ int x,y,step; }now,top,nxt; queue<node>q; int ans[N][N]; int n,m,startx,starty; inline int read() {
int x=0;char c=getchar(); while(c<0||c>9)c=getchar(); while(c>=0&&c<=9)x=x*10+c-0,c=getchar(); return x; } inline void bfs(int x,int y) { ans[x][y]=-3; now.x=x; now.y=y; now.step=0; q.push(now); while(!q.empty()) { top=q.front(); q.pop();
for(int i=0;i<8;i++) { int x=top.x+xd[i]; int y=top.y+yd[i]; if(x>0&&x<=n&&y>0&&y<=m&&!ans[x][y]) { ans[x][y]=top.step+1; nxt.x=x; nxt.y=y; nxt.step=top.step+1; q.push(nxt); } } } } int main() { n=read(); m=read(); startx=read(); starty=read(); bfs(startx,starty); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(ans[i][j]==-3) printf("%-5d",0); else if(ans[i][j]==0) printf("%-5d",-1); else printf("%-5d",ans[i][j]); } printf("\n"); } return 0; }



P1443 馬的遍歷