题目描述:输入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");
}
}