深搜最短路径

package 万能的搜索;

import java.util.Scanner;

/**
 * 深搜最短路径
 * 
 * 
 * */
public class Demo02 {
	
	static int[][] a;
	static int[][] b;
	static int min,q,p,m,n;

	public static void dfs(int startx,int starty,int step) {
		// 先写退出条件
		if(startx == p && starty==q) {
			if(step < min) {
				min = step;     
			}
			return ;
		}
		//记录下一个坐标
		int tx,ty;
		// 相当于一个方向矩阵
		int next[][]= {{0,1},{1,0},{0,-1},{-1,0}};
		
		
		//枚举各种情况
		for(int k=0;k<4;k++) {
			// 先移动
			tx = startx + next[k][0];
			ty = starty + next[k][1];
			// 将不合适的去掉
			if(tx < 1 || tx >n || ty<1 || ty>m) { 
				continue;
			}
			
			if(b[tx][ty]==0 && a[tx][ty]==0) {
				b[tx][ty] = 1;
				dfs(tx,ty,step+1);
				b[tx][ty] =  0; // 因为就当你找到了,但可能不是最短的,所以需要取消标记
			}
			
		}
	}
	
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		min = Integer.MAX_VALUE;
		 n = in.nextInt();
		 m = in.nextInt();
		a = new int[n+1][m+1];
		b = new int[n+1][m+1];
		for(int i=1;i<=n;i++) { 
			for(int j=1;j<=m;j++) {
				a[i][j] = in.nextInt();
			}	
		}
	
		
		int startx = in.nextInt();
		int starty = in.nextInt();
		 p = in.nextInt();
		 q = in.nextInt();
		b[startx][starty] = 1;
		dfs(startx,starty,0);
		System.out.println(min);
	}
	
}


/*
 * 
 *  5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
 * 答案是:7
 * */
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值