走出迷宫,数组越界
程序代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); //LinkedQueue<Integer> lq = new LinkedQueue<Integer>(); while(in.hasNext()){ int maze[][]=new int[5][5]; for(int i=0;i<5;i++){ for(int j=0;j<5;j++) maze[i][j]=in.nextInt(); } //System.out.println(); LinkedQueue s = new LinkedQueue(); //LinkedQueue s1 = new LinkedQueue(); int a = work(maze); // while(!s.isEmpty()){ Point p = (Point) s.dequeue(); System.out.println("("+p.x+", "+p.y+")"); //} //System.out.println("Case "+(co++)+":"+work(a,b,an,bn)); } } public static int work(int[][] maze){ //boolean flag[][] = new boolean[9][9];//标记是否被访问过 //int d[][] = {{ 1, 0, -1, 0 },{ 0, 1, 0, -1 }}; //int[][] move = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}}; //int step = 0; LinkedQueue<Point> q = new LinkedQueue<Point>(); int[][] move = {{0,1},{1,0},{0,-1},{-1,0}}; Point p = new Point(1,1,-1); q.enqueue(p);//第一个点入队 //flag[a][b]=true;//标记是否走过 while(!q.isEmpty()){ p = q.dequeue(); //出队 int x = p.x; int y = p.y; int d = p.d; while(d<4){ int i = x+move[d][0]; int j = y+move[d][1]; if(maze[i][j]==0){//该点可达 p = new Point(i,j,d); q.enqueue(p); x = i; y = j; maze[x][y]=-1;//到达新点,标志已经可达 if(x==5&&y==5) return 1;//到达出口,迷宫有路 else d = 0;//重新初始化方向 }else d++;//改变方向 } } return 0; } } class Point{ int x,y,d; public Point(int x,int y,int d){ this.x = x;//横坐标 this.y = y;//纵坐标 this.d = d;//方向 } //public String toString() { // return "(" + x + "," + y + ")"; //} } class LinkedQueue<T>{ Node<T> front,rear; public LinkedQueue(){ this.front = this.rear = null; } public boolean isEmpty(){ return this.front == null && this.rear == null; } public void enqueue(T x){ if(x==null) return ; Node<T> q = new Node<T>(x,null); if(this.front == null) this.front = q; else this.rear.next = q; this.rear = q; } public T dequeue(){ if(isEmpty()) return null; T temp = front.data; this.front = front.next; if(this.front==null) this.rear = null; return temp; } } class Node<T>{ T data; Node<T> next; public Node(){ this(null,null); } public Node(T data, Node<T> next) { this.data = data; this.next = next; } }
运行之后提示红色这两行越界Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Main.work(Main.java:43)
at Main.main(Main.java:18)
求教