1. 程式人生 > >java實現走迷宮演算法

java實現走迷宮演算法

程式碼實現了 讀取檔案中迷宮地圖,列印迷宮地圖並找到一條出口。第一次寫java程式碼,留著紀念。

用一個檔案儲存 N*N的迷宮地圖,E代表的是入口,X代表的是出口、*代表可以走,1代表不可以走。每次在原座標的基礎上,搜尋上下左右四個方向的路徑,是否可行。直到找到出口。找到一條路徑就結束,最後列印一條路徑(不一定是最優路徑)。

6
1 * E 1 * *
1 * * * * *
1 * 1 * * X
* * 1 1 * 1
* 1 * * * *
* * * 1 1 1
程式碼如下:

</pre><pre name="code" class="java">package com.maze.path;

import java.util.Stack;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

class Step{
    int x,y;
    public Step(int x,int y) {
        this.x = x;
        this.y = y;
    }
}

public class Path {
	private int inx,iny; //the location of Entrance and Exit
//	private char map[][]; 
	static  int dir[][] = {{0,1},{0,-1},{1,0},{-1,0}}; //4 directories each point
	static  int N; //maze size=N*N 
	
	public static char[][] readMap(String filePath){
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ 
                    InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);
                    BufferedReader bReader = new BufferedReader(read);
                    String lineTxt = null;
                    String array = "";
                    while((lineTxt = bReader.readLine()) != null){   
                        array += lineTxt;
                    }
                    read.close();
                    array = array.replace(" ", "");
                    
                    int i = 0;	 
                    int n = Integer.parseInt(array.charAt(i++)+""); 
                    Path.N = n;
                    //System.out.println("n:6 "+n+"i:0 "+i);
                    
                    char[][] cArray = new char[n][n] ;
                    for(int col=0;col<6;col++){
                    		for(int row=0;row<6;row++){	   
                    		char a = array.charAt(i);
                    		cArray[col][row] = a;
                    		i++;
                    		//System.out.println(i+"a:"+a);
                    		if(i>array.length()) {
                    			System.out.println("Sorry,this maze is not N*N standard size");
                    			break;
                    			}                  		
                    	     }
                    	}	                    
                    return cArray;          
        } else {
            System.out.println("can't find the file");	            
        }
        } catch (Exception e) {// readLine() method must handle java.io.IOException Exception 
            System.out.println("run error"+e.getMessage());
            e.printStackTrace();
        }
		return null;     
    }

	public static void main(String[] args) {
		String filePath = "E:\\files\\Maze.txt";		
		int dirs[][] = Path.dir;
		Path path = new Path();
		Stack<Step> ss = new Stack<Step>();		
		char maps[][] = readMap(filePath);		
		if(maps == null || maps.length == 0) 
			System.out.println("read map failed ");		
		
		path.printmaze(maps);
		path.setEntrance(maps);
		int inxs = path.inx;
		int inys = path.iny;
		path.findPath(maps, inxs, inys, dirs, ss);

	}
	
	public void setEntrance (char[][] map) {
		for(int i=0;i<N;i++)
			for(int j=0;j<N;j++)
				if(map[i][j]=='E' || map[i][j]=='e') {
					inx = j;
					iny = i;
				}		
	}
	
	public void printmaze(char[][] map){
		for(int i=0;i<N;i++)
		{
			for(int j=0;j<N;j++){
				System.out.print(map[i][j]+" ");				
			}
			System.out.println(""); 
			
		}
		
	}
	
	public void printmaze(int[][] map){
		for(int i=0;i<4;i++)
		{
			for(int j=0;j<2;j++){
				System.out.print(map[i][j]+" ");				
			}
			System.out.println(""); 
			
		}
		
	}
	
	public void findPath(char[][] map,int inx, int iny,int[][] dir,Stack<Step> s) {

		Step temp = new Step(inx,iny);
		s.push(temp);		
		while (!s.empty()) {
			//System.out.println("k = " + k++ );
			int d = 0;
			int mark = 0;//mark the first pushStack
			temp = s.pop();
			int x = temp.x;
			int y = temp.y;			
			//System.out.println("temp.x = "+ temp.x+ ", temp.y = "+ temp.y);
			
			while (d < 4) {
				//System.out.println("d = " + d);
				int j = x + dir[d][0];
				int i = y + dir[d][1];
				
				if(i < 0 || i >= N || j < 0 ||j >= N ) {
					d++;					
				} else if (map[i][j] == 'X' || map[i][j] == 'x'){
					if(s.empty()){						
						System.out.println("no valid path");	
						return;
					}
					else {
						if(mark == 0){
							temp = new Step(x,y);
							s.push(temp);
						}
						System.out.print("("+j+","+i+") ");
						while(!s.empty()){
							Step stp = s.pop();
							System.out.print("("+stp.x+","+stp.y+") ");
						}							
						return ;
					}					
				} else if (map[i][j]=='*') {					
					if(mark == 0){
						temp = new Step(x,y);
						s.push(temp);
					}				
					x = j;
					y = i;
					temp = new Step(x,y);
					s.push(temp);
					d++;
					mark=1;
					map[i][j] = 'v';//change the status of the point which has been visited
				} else 
					d++;
			}		
		}
		if(s.empty()) System.out.println("no valid path");
	}

}