走迷宫

来源:互联网 发布:中南大学湖南大学知乎 编辑:程序博客网 时间:2024/05/01 05:08
package OJ;


import java.util.*;


public class Bully {


/*
* 走迷宫
* 它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从
* 左上角到右下角的最短路线。入口点为[0,0],既第一空格是可以走的路。
* Input
* 一个N × M的二维数组,表示一个迷宫。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
* Output
* 左上角到右下角的最短路径,格式如样例所示。
* Sample Input
* 0 1 0 0 0
* 0 1 0 1 0
* 0 0 0 0 0
* 0 1 1 1 0
* 0 0 0 1 0
* Sample Output
* (0, 0)
* (1, 0)
* (2, 0)
* (2, 1)
* (2, 2)
* (2, 3)
* (2, 4)
* (3, 4)
* (4, 4)
  * */

private static ArrayList<String> al = new ArrayList<String>();


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String str = sc.nextLine();
int n = Integer.parseInt(str.substring(0, 1));
int m = Integer.parseInt(str.substring(str.length()-1));

int[][] graph = new int[n][m];

StringBuffer sb = new StringBuffer();
int[][] visit = new int[n][m];

for(int i=0;i<n;i++){
str = sc.nextLine();
String[] s = str.split(" ");
for(int j=0;j<m;j++){
graph[i][j] = Integer.parseInt(s[j]);
}
}

outFromHere(m,n,graph,0,0,sb,visit);

Iterator<String> it = al.iterator();
int len = 1000;
String re = "";

while(it.hasNext()){
String temp = it.next();
if(temp.length()<len){
len = temp.length();
re = temp;
}
}
String[] s = re.split(" ");
for(int i=0;i<s.length;i++){
sop("("+s[i].charAt(0)+","+s[i].charAt(1)+")");
}



}


private static void outFromHere(int m,int n,int[][] graph, int i, int j,
StringBuffer sb, int[][] visit) {
visit[i][j] = 1;
sb.append(i+""+j+" ");

if(i==n-1 && j==m-1)
al.add(sb.toString());
else{
if(i+1<n){
if(graph[i+1][j]==0 && visit[i+1][j]==0)
outFromHere(m,n,graph,i+1,j,sb,visit);
}
if(j+1<m){
if(graph[i][j+1]==0 && visit[i][j+1]==0)
outFromHere(m,n,graph,i,j+1,sb,visit);
}
if(i-1>=0){
if(graph[i-1][j]==0 && visit[i-1][j]==0)
outFromHere(m,n,graph,i-1,j,sb,visit);
}
if(j-1>=0){
if(graph[i][j-1]==0 && visit[i][j-1]==0)
outFromHere(m,n,graph,i,j-1,sb,visit);
}
}

visit[i][j] = 0;
sb.setLength(sb.length()-1-String.valueOf(i).length()-String.valueOf(j).length());


}


public static void sop(Object o){
System.out.println(o);
}


}
0 0
原创粉丝点击