蓝桥杯 Java 深度优先

import java.util.Scanner;

import com.sun.org.apache.bcel.internal.generic.NEW;


public class 深度优先 {

	/**
	 * 迷宫问题
	 * 一个n*m的迷宫,走到某处的最短路径 1表示有障碍物
	 * 输入格式
	 * 5 4           5行4列
	 * 0 0 1 0                迷宫第图 1表示障碍物
	 * 0 0 0 0
	 * 0 0 1 0
	 * 0 1 0 0
	 * 0 0 0 1
	 * 1 1 4 3       1 1 表示起点  4 3 表示达到的位置
	 * 输出格式
	 * 7              最短走7次
	 */
	
	static int[][] a=new int[51][51];      // 迷宫 
	static int[][] book=new int[51][51];   // 标记 
	static int min=51;                // 最短路径长度
	static int n,m;
	static int endx,endy;            // 到达位置
	public static void main(String[] args) {
		int startx,starty;        // 起始位置
		
		Scanner scanner=new Scanner(System.in);
	    n=scanner.nextInt();        // n行
		m=scanner.nextInt();        // m列
        // 接收迷宫地图
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= m; j++) {
				a[i][j]=scanner.nextInt();
			}
		}
		
		// 读入起始点和到达点
		startx=scanner.nextInt();
		starty=scanner.nextInt();
		endx=scanner.nextInt();
		endy=scanner.nextInt();
		
		// 从起始点开始搜索
		book[startx][starty]=1;   // 先标记该位置已遍历过
		dfs(startx,starty,0);
		System.out.println(min);
	}
     
	 // x表示起点x坐标,y表示起点y坐标,step走的步数
     public static void dfs(int x,int y,int step){
    	 int[][] next={{0,1},   // 向右走
    			       {1,0},   // 向下走
    			       {0,-1},  // 向左走
    			       {-1,0},  // 向上走
    			       };
    	 
    	 int tx,ty;
    	 
    	 // 边界条件,判断是否到达点
    	 if (x==endx&&y==endy) {
			// 更新最小值
    		 if(step<min){
    			 min=step;
    		 }
    		 return;
		}
    	 
    	 // 遍历所有走法,四种
    	 for (int i = 0; i < 4; i++) {
			tx=x+next[i][0];
			ty=y+next[i][1];    // 下一点坐标
			// 判断是否越界
			if (tx<1||tx>n||ty<1||ty>m) {
				continue;
			}
			
			// 判断该点是否有障碍物或者遍历过’
			if (a[tx][ty]==0&&book[tx][ty]==0) {
				book[tx][ty]=1;  // 标记该点遍历过
				dfs(tx, ty, step+1);
				book[tx][ty]=0;  // 还原
			}
			
		}
     }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

B&Y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值