最短路径问题

21 篇文章 0 订阅

题目来源:http://acm.hdu.edu.cn/vcontest/vtl/problem/showproblem/vtlid/4642/problemid/1011




java代码如下:

public class Shortest {
//http://acm.hdu.edu.cn/vcontest/vtl/problem/showproblem/vtlid/4642/problemid/1011
	private int[][] table=new int[10][10];
	private boolean[][] map=new boolean[10][10];
	private void initTable(){
		int i=5;
		int j=4;
		int number=2;
		table[i][j]=1;
		int a=1,b=2;
		while(number<73){
			for(int d=0;d<a;d++){
				table[i][++j]=number++;
			}
			for(int d=0;d<a;d++){
				table[--i][j]=number++;
			}
			a+=2;
			for(int d=0;d<b;d++){
				table[i][--j]=number++;
			}
			for(int d=0;d<b;d++){
				table[++i][j]=number++;
			}
			b+=2;		
		}
		for(int d=0;d<a;d++){
			table[i][++j]=number++;
		}
		for(int d=0;d<a;d++){
			table[--i][j]=number++;
		}
		for(int d=0;d<b-1;d++){
			table[i][--j]=number++;
		}
	}
	private void initMap(){
		map[0][3]=true;
		map[1][4]=map[1][6]=true;
		map[2][1]=map[2][7]=map[2][9]=true;
		map[3][0]=map[3][2]=map[3][6]=true;
		map[4][3]=map[4][5]=map[4][7]=true;
		map[5][2]=map[5][5]=map[5][6]=map[5][8]=true;
		map[6][1]=map[6][3]=true;
		map[7][0]=map[7][4]=true;
		map[8][1]=map[8][5]=map[8][9]=true;
		map[9][0]=map[9][6]=true;
	}
	private int aim;
	public Shortest(int a,int b){
		initTable();
		initMap();
		aim=b;
		for(int i=0;i<10;i++)
			
			for(int j=0;j<10;j++){
				if(table[i][j]==a){
					process(i,j,0);
					break;
				}
			}
		if(bestPath==1000000){
			System.out.println("impossible");
		}else{
			System.out.println(bestPath);
		}
	}
	//表示很远
	private int bestPath=1000000;
	
	private void process(int i,int j,int path){
		if(table[i][j]==aim){
			if(path<bestPath){
				bestPath=path;
			}
		}
		map[i][j]=true;
		//没有数据 有数据的为true,
		if(i-1>=0&&!map[i-1][j]){
			//向上	
			process(i-1,j,path+1);
		}
		if(i+1<=9&&!map[i+1][j]){
			//向下
			process(i+1,j,path+1);
		}
		if(j-1>=0&&!map[i][j-1]){
			//向左
			process(i,j-1,path+1);
		}
		if(j+1<=9&&!map[i][j+1]){
			//向右
			process(i,j+1,path+1);
		}
		map[i][j]=false;
	}
	public static void main(String[] args) {
		int start=9;
		int end=32;
		new Shortest(start,end);
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值