跳馬問題

總時間限制: 1000ms 內存限制: 65535kB
描述


在中國象棋中,棋子活動的場所,叫做"棋盤",在長方形的平面上,繪有九條平行的豎線和十條平行橫線相交組成,共九十個交叉點,棋子就擺在這些交叉點上。中間第五、第六兩橫線之間未畫豎線的空白地帶,稱爲"河界",整個棋盤就以"河界"分爲相等的兩部分;兩方將帥坐鎮、畫有"米"字方格的地方,叫做"九宮"。

中國象棋中,馬是威力很大的棋子。馬走動的方法是一直一斜,即先橫着或直着走一格,然後再斜着走一個對角線,俗稱"馬走斜"。馬一次可走的選擇點可以達到四周的八個點,故有"八面威風"之說。

我們約定最左下角點的座標爲(0,0),則最右上角的座標爲(9, 8)。上圖中馬在座標(2, 2)處。它走一步可以到達座標點(1, 0),(0, 1),(0, 3),(1, 4),(3, 4),(4, 3),(4, 1)或(3,0)。如下圖所示。



我們約定當前棋盤上只有一個馬,給出起點座標和終點座標,求從起點到終點,馬最少要走幾步?



輸入
4個整數,前2個數表示起點座標,後2個數表示終點座標。
輸出
一個整數,表示從起點到終點最少需要走的步數。
樣例輸入
2 2 5 2
樣例輸出

3


#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;


int st1,st2,end1,end2;
struct chess
{
	int x,y;
	int step;
} ;

bool map[15][15];
int bfs()
{
	chess a,next;
	queue<chess> Q;
	a.x=st1;
	a.y=st2;
	a.step=0;
	Q.push(a);
	map[st1][st2]=1;
	while(!Q.empty())
	{
		a=Q.front();
		
		if(a.x==end1&&a.y==end2)
		 return a.step;
		Q.pop();
		next=a;
		next.x=a.x+1; next.y=a.y+2;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		
		next.x=a.x+2; next.y=a.y+1;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		next.x=a.x+2; next.y=a.y-1;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		next.x=a.x+1; next.y=a.y-2;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		next.x=a.x-1; next.y=a.y-2;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		next.x=a.x-2; next.y=a.y-1;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		next.x=a.x-2; next.y=a.y+1;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		next.x=a.x-1; next.y=a.y+2;
		if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
		if(!map[next.x][next.y])
		{
			next.step=a.step+1;
			map[next.x][next.y]=1;
			Q.push(next); 
		}
		
		
	}
	

}

int main()
{
	while(scanf("%d%d%d%d",&st1,&st2,&end2,&end1)!=EOF)
  		{
  			

		int i;
		memset(map,0,sizeof(map));
		for(int i=0;i<11;i++)
		 map[i][0]=map[i][11]=1;
		for(int i=0;i<12;i++)
		 map[0][i]=map[10][i]=1; 
		 

		
		 st1++;st2++;end1++;end2++;
		
		printf("%d\n",bfs());
	
		  }
}






發佈了39 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章