题目:

输入数据:
6 8
0 1 0 1 0 0 0 1
1 0 0 1 1 0 1 0
0 1 1 0 0 1 1 1
1 0 0 1 1 0 0 1
1 0 0 0 1 1 0 1
0 1 1 1 0 0 0 0
输出数据:
(0,0)->(1,1)->(1,2)->(2,3)->(2,4)->(3,5)->(4,6)->(5,7)
算法思路:将所有方向用dir数组装起来,将顶点加入队列,进入循环,循环出口:为x,y坐标等于设置的出口坐标,每次将各个方位的坐标加入队列中并做上标记(防止重复走,减少计算量),最先到达循环出口的即为最小路径.
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
//能走的各个方向
static int dir[][] = {{-1,0},{0,-1},{1,0},{0,1},{1,1},{1,-1},{-1,1},{-1,-1}};
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
while(cin.hasNext()){
int n=cin.nextInt();
int m=cin.nextInt();
boolean locate [][] = new boolean[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int judge = cin.nextInt();
if(judge == 1){
locate[i][j] = true;
}
}
}
System.out.println(find(n,m,locate));
}
}
public static String find(int n,int m,boolean locate [][]){
LinkedList<Data> q = new LinkedList<Data>();
q.add(new Data(0,0,""));
locate [0][0] = true;
while(!q.isEmpty()){
Data t = q.poll();
if(t.x==n-1 && t.y==m-1){
return t.str;
}else{
for(int i=0;i<dir.length;i++){
int xx = t.x + dir[i][0];
int yy = t.y + dir[i][1];
if(xx>=0 && xx <n && yy >=0 && yy<m && locate[xx][yy]==false){
q.add(new Data(xx,yy,t.str));
locate[xx][yy] = true;
}
}
}
}
return null;
}
}
class Data{
int x;
int y;
String str;
public Data(int x, int y,String str) {
super();
this.x = x;
this.y = y;
if(x==0&&y==0){
this.str = "("+x+","+y+")";
}else{
this.str = str+"->("+x+","+y+")";
}
}
}