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

馬的遍歷

題目描述
有一個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

一開始用dfs寫的,超時,然後該成了bfs

#include<stdio.h>
#include<queue>
#include<algorithm>
#include<string.h>
using namespace std;
int n,m,x,y;
int dir[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{-1,-2},{1,-2}};//馬走日的八個方向 
int vis[410][410],step[410][410];

bool check(int x,int y) //檢視是否出邊界 
{
	if(x>=0&&x<n&&y>=0&&y<m)
		return 1;
	return 0;
}

struct node
{
	int x,y;
};

void bfs(int x,int y,int k)
{
	step[x][y]=k;//起始位置入隊 
	vis[x][y]=0;
	queue<node>q;
	node now,next;
	now.x=x;
	now.y=y;
	q.push(now);
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		for(int i=0;i<8;i++)
		{
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			if(check(next.x,next.y))
			{
				if(vis[next.x][next.y])//沒有走過,入隊,記錄步數,標記為走過 
				{
					q.push(next);
					vis[next.x][next.y]=0;
					step[next.x][next.y]=step[now.x][now.y]+1;
				}
			}
		}
	}
}

int main()
{
	while(scanf("%d%d%d%d",&n,&m,&x,&y)!=EOF)
	{
		x-=1;//我寫的陣列從0開始的 
		y-=1;
		memset(vis,1,sizeof(vis));
		memset(step,-1,sizeof(step));
		bfs(x,y,0);
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				printf("%-5d",step[i][j]);
			}
			printf("\n");
		}
	}
	return 0;
}

(剣を習いたい)