迷宫问题--java

 

package test4;

import java.util.Stack;

public class Maze {
 private class Point{
  int x = 0;
  int y = 0;
  public String toString(){
   return “{” + x +”,” + y + “}”;
  }
  public boolean equals(Point p){
   return (this.x == p.x)&&(this.y == p.y);
  }
  public Point(int x,int y){
   this.x = x;
   this.y = y;
  }
 }
 private int[][] maze =  new int[][] {{ 0, 0, 1, 0, 1, 0, 1, 0, 1, 0},
    { 0, 0, 1, 1, 1, 0, 0, 0, 1, 0 },
    { 0, 1, 0, 0, 1, 0, 0, 0, 0, 1 },
    { 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 },
    { 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 },
    { 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 },
    { 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 },
    { 1, 1, 1, 0, 1, 1, 0, 1, 0, 0 }
   };
 private Stack<Point> stack = new Stack<Point>();
 public Maze(){
  
 }
 public Maze(int[][] maze){
  this.maze = maze;
 }
 public void go(){
  Point out = new Point(maze.length-1,maze[0].length-1);//出口
   Point in = new Point(0,0);//入口
  Point curNode = in;//当前节点
  Point nextNode = null;//下一个访问点
  while(!curNode.equals(out)){
   nextNode = new Point(curNode.x,curNode.y);
   if((curNode.x + 1) < maze.length && maze[curNode.x + 1][curNode.y] == 0){
    nextNode.x++;
   }else if((curNode.y + 1)<maze[0].length && maze[curNode.x][curNode.y + 1] == 0){
    nextNode.y ++ ;
   }else if((curNode.x – 1) >= 0 && maze[curNode.x – 1][curNode.y] == 0){
    nextNode.x– ;
   }else if(curNode.y – 1 >= 0 && maze[curNode.x][curNode.y -1] == 0){
    nextNode.y–;
   }else{
    maze[curNode.x][curNode.y] = 3;
    if(stack.isEmpty()){
     System.out.println(“No path”);
     return;
    }
    curNode = stack.pop();
    continue;
   }
   stack.push(curNode);
   maze[curNode.x][curNode.y] = 2;
   curNode = nextNode;
  }
  if(nextNode.equals(out)){
   stack.push(nextNode);
   maze[nextNode.x][nextNode.y] = 2;
  }
  for(int i =0 ;i < stack.size() ;i ++){
   System.out.println(stack.elementAt(i));
  }
 }
 public static void main(String[] args){
  new Maze().go();
 }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/d_x_program/article/details/7353385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞