ShortestPath

题目描述:输入n,m,即有n行m列的矩阵;s代表开始,e代表结束,"."代表可走,"#"代表不可走,求从s到e的最短路径.若无,输出-1.

输入:

       4 5

   . . s # e

   . # . # .

   # . . # .

   . . . . .

输出:8

package 深搜;

import java.util.Scanner;
public class 最短路径问题 {
    static char map[][]=new char[100][100];//存储
    static int vis[][]=new int[100][100];//标记
    static int b[][]={{1,0},{-1,0},{0,-1},{0,1}};//方向
    static int n,m,d=0;
    static int max=2147480000;
    static boolean flag=false;
    static void dfs(int x,int y,int dep){
    	if(dep>d)return; //进行优化########
    	if(map[x][y]=='e'){
    		flag=true;        //加标记,如果走不到e,输出-1
    		d=dep;
    		return;
    	}
    	for(int i=0;i<4;i++){
    		int xx=x+b[i][0];
    		int yy=y+b[i][1];
    		if(xx<0 || yy<0 || xx>=n || yy>=m)continue; //越界
    		if(map[xx][yy]=='#' || vis[xx][yy]!=0)continue; //此路不通或者已经走过
    		vis[xx][yy]=1;
    		dfs(xx,yy,dep+1);
    		vis[xx][yy]=0;
    	}
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
      Scanner scan=new Scanner(System.in);
      n=scan.nextInt();
      m=scan.nextInt();
      String str=null;
      int x=0,y=0;
      for(int i=0;i<n;i++){
    	  str=scan.next();
    	  for(int j=0;j<m;j++){
    		  map[i][j]=str.charAt(j);
    		  if(map[i][j]=='s'){
    			  x=i;
    			  y=j;
    		  }
    	  }
      }
      d=max;
      dfs(x,y,0);
      if(flag)
          System.out.println(d);
      else
    	  System.out.println("-1");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值