UVA 439 Knight Moves 基础BFS

题意是:给定一个8*8的棋盘然后给你起点和终点的坐标让你求骑士(也就是中国象棋中的马,只不过没有拌腿的限制)从起点走到终点的最短距离

思路就是用BFS从起点开始按照骑士的走法遍历棋盘,知道走到终点。

//注意起点和终点在一起的情况

import java.util.ArrayList;
import java.util.Scanner;

//BFS求解最小距离
public class Main {
	static int inc[][]={{-1,2},{1,2},{2,1},{2,-1},{-2,-1},{-1,-2},{1,-2},{-2,1}};
	static int map[][]=new int[9][9];
	static boolean mark[][]=new boolean[9][9];
	static String start,end;
	class Node
	{
		int x,y;
		int num;
		Node(int x,int y)
		{
			this.x=x;
			this.y=y;
		}
	}
	 void run() {
		
		Scanner in=new Scanner(System.in);
		while(in.hasNext())
		{
			start=in.next();
			end=in.next();
			int x1=start.charAt(0)-'a'+1;
			int y1=start.charAt(1)-'0';
			int x2=end.charAt(0)-'a'+1;
			int y2=end.charAt(1)-'0';
			Node star=new Node(x1,y1);
		//注意终点和起点在一起的时候	
			if(x1==x2&&y1==y2)
			{
				System.out.println("To get from "+start+" to "+end+" takes "+0+" knight moves.");
			}else
			{
			for(int i=1;i<=8;i++)
			{
				for(int j=1;j<=8;j++)
				{
					if(i==x1&&j==y1)
						map[i][j]=1;
					else if(i==x2&&j==y2)
						map[i][j]=2;
					else	
					map[i][j]=0;
				}
			}
			
			BFS(star);
			
			}
			
		}
		
	}
	
	void BFS(Node star)
	{
		for(int i=1;i<=8;i++)
			for(int j=1;j<=8;j++)
				mark[i][j]=false;
		
		ArrayList<Node> lis=new ArrayList<Node>();
		int ans=0;
		star.num=0;
		
		Node cur,next;
		
		int a=star.x;
		int b=star.y;
		
		lis.add(star);
		mark[a][b]=true;
		
		while(!lis.isEmpty())
		{
			cur=lis.remove(0);
			for(int i=0;i<8;i++)
			{
				int t1=cur.x+inc[i][0];
				int t2=cur.y+inc[i][1];
				next=new Node(t1,t2);
				if(t1>=1&&t1<=8&&t2>=1&&t2<=8&&!mark[t1][t2])
				{
					int flag=map[t1][t2];
					next.num=cur.num+1;
					mark[t1][t2]=true;
					lis.add(next);
					if(flag==2)
					{
						ans=next.num;
						System.out.println("To get from "+start+" to "+end+" takes "+ans+" knight moves.");
						return;
					}
				}
				
			}
			
			
		}
	}
	public static void main(String[] args) {
		new Main().run();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值