迷宮問題解法彙總

from:http://www.cnblogs.com/rollenholt/archive/2011/08/23/2151202.html

java寫的回溯法求迷宮問題

問題描述:

[實驗目的]

綜合運用數組、遞歸等數據結構知識,掌握、提高分析、設計、實現及測試程序的綜合能力。

[實驗內容及要求]

以一個M×N的長方陣表示迷宮,0和1分別表示迷宮中的通路和障礙。設計一個程序,對任意設定的迷宮,求出一條從入口到出口的通路,或得出沒有通路的結論。

(1)    根據二維數組,輸出迷宮的圖形。

(2)    探索迷宮的四個方向:RIGHT爲向右,DOWN向下,LEFT向左,UP向上,輸出從入口到出口的行走路徑。

[測試數據]

左上角(1,1)爲入口,右下角(8,9)爲出口。

0

0

1

0

0

0

1

0

0

0

1

0

0

0

1

0

0

0

1

0

1

1

0

1

0

1

1

1

0

0

1

0

0

0

0

1

0

0

0

0

0

1

0

0

0

1

0

1

0

1

1

1

1

0

0

1

1

1

0

0

0

1

0

1

1

1

0

0

0

0

0

0

[實現提示]

可使用回溯方法,即從入口出發,順着某一個方向進行探索,若能走通,則繼續往前進;否則沿着原路退回,換一個方向繼續探索,直至出口位置,求得一條通路。假如所有可能的通路都探索到而未能到達出口,則所設定的迷宮沒有通路。

運行示例:

import java.util.*;
 
class Position{
    public Position(){
 
    }
 
    public Position(int row, int col){
        this.col = col;
        this.row = row;
    }
 
    public String toString(){
        return "(" + row + " ," + col + ")";
    }
 
    int row;
    int col;
}
 
class Maze{
    public Maze(){
        maze = new int[15][15];
        stack = new Stack<Position>();
        p = new boolean[15][15];
    }
 
    /*
     * 構造迷宮
     */
    public void init(){
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入迷宮的行數");
        row = scanner.nextInt();
        System.out.println("請輸入迷宮的列數");
        col = scanner.nextInt();
        System.out.println("請輸入" + row + "行" + col + "列的迷宮");
        int temp = 0;
        for(int i = 0; i < row; ++i) {
            for(int j = 0; j < col; ++j) {
                temp = scanner.nextInt();
                maze[i][j] = temp;
                p[i][j] = false;
            }
        }
    }
 
    /*
     * 回溯迷宮,查看是否有出路
     */
    public void findPath(){
        // 給原始迷宮的周圍家一圈圍牆
        int temp[][] = new int[row + 2][col + 2];
        for(int i = 0; i < row + 2; ++i) {
            for(int j = 0; j < col + 2; ++j) {
                temp[0][j] = 1;
                temp[row + 1][j] = 1;
                temp[i][0] = temp[i][col + 1] = 1;
            }
        }
        // 將原始迷宮複製到新的迷宮中
        for(int i = 0; i < row; ++i) {
            for(int j = 0; j < col; ++j) {
                temp[i + 1][j + 1] = maze[i][j];
            }
        }
        // 從左上角開始按照順時針開始查詢
 
        int i = 1;
        int j = 1;
        p[i][j] = true;
        stack.push(new Position(i, j));
        while (!stack.empty() && (!(i == (row) && (j == col)))) {
 
            if ((temp[i][j + 1] == 0) && (p[i][j + 1] == false)) {
                p[i][j + 1] = true;
                stack.push(new Position(i, j + 1));
                j++;
            } else if ((temp[i + 1][j] == 0) && (p[i + 1][j] == false)) {
                p[i + 1][j] = true;
                stack.push(new Position(i + 1, j));
                i++;
            } else if ((temp[i][j - 1] == 0) && (p[i][j - 1] == false)) {
                p[i][j - 1] = true;
                stack.push(new Position(i, j - 1));
                j--;
            } else if ((temp[i - 1][j] == 0) && (p[i - 1][j] == false)) {
                p[i - 1][j] = true;
                stack.push(new Position(i - 1, j));
                i--;
            } else {
                stack.pop();
                if(stack.empty()){
                    break;
                }
                i = stack.peek().row;
                j = stack.peek().col;
            }
 
        }
 
        Stack<Position> newPos = new Stack<Position>();
        if (stack.empty()) {
            System.out.println("沒有路徑");
        } else {
            System.out.println("有路徑");
            System.out.println("路徑如下:");
            while (!stack.empty()) {
                Position pos = new Position();
                pos = stack.pop();
                newPos.push(pos);
            }
        }
         
        /*
         * 圖形化輸出路徑
         * */
         
        String resault[][]=new String[row+1][col+1];
        for(int k=0;k<row;++k){
            for(int t=0;t<col;++t){
                resault[k][t]=(maze[k][t])+"";
            }
        }
        while (!newPos.empty()) {
            Position p1=newPos.pop();
            resault[p1.row-1][p1.col-1]="#";
         
        }
         
        for(int k=0;k<row;++k){
            for(int t=0;t<col;++t){
                System.out.print(resault[k][t]+"\t");
            }
            System.out.println();
        }
     
 
    }
 
    int maze[][];
    private int row = 9;
    private int col = 8;
    Stack<Position> stack;
    boolean p[][] = null;
}
 
class hello{
    public static void main(String[] args){
        Maze demo = new Maze();
        demo.init();
        demo.findPath();
    }
}

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class BFS {

	/**
	 * @param args
	 */
	private static final int M = 4;
	private static final int N = 4;
	int[][] maze;//迷宮佈局:1表示障礙物
	int[][] visit;//標記是否已經訪問過
	int[][] stepArr = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; //方向:左上右下
	class Node{
		int x, y;
		int step;
		int preX, preY;
		Node(int x, int y, int preX, int preY, int step){
			this.x = x;
			this.y = y;
			this.preX = preX;
			this.preY = preY;
			this.step = step;
		}
	}
	public BFS() {
		// TODO Auto-generated constructor stub
		maze = new int[][]{{0,0, 1, 1},
								{0, 0,0, 1},
								{1, 1,0, 1},
								{0, 0, 0, 0}};
		visit = new int[4][4];
	}
	
	public int bfs(){
		Node node = new Node(0, 0, -1, -1, 0);
		Queue<BFS.Node> queue = new LinkedList<BFS.Node>();
		Stack<BFS.Node> stack = new Stack<BFS.Node>();
		queue.offer(node);
		//visit[0][0] = 1;
		while(!queue.isEmpty()){
			Node head = queue.poll();
			stack.push(head); //用於回溯路徑
			visit[head.x][head.y] = 1;
			for(int i = 0; i < 4; i++){
				int x = head.x + stepArr[i][0];
				int y = head.y + stepArr[i][1];
				//exit
				if(x == M -1 && y == N -1 && maze[x][y] == 0 && visit[x][y] == 0){
					//打印路徑
					Node top = stack.pop();
					System.out.println("steps:" + (top.step + 1));
					System.out.println("the path:");
					System.out.println((M - 1) + "," + (N - 1));
					System.out.println(top.x + "," + top.y);
					int preX = top.preX;
					int preY = top.preY;
					while(!stack.isEmpty()){
						top = stack.pop();
						if(preX == top.x && preY == top.y){
							System.out.println(preX + "," + preY);
							preX = top.preX;
							preY = top.preY;
						}
						
					}
					return 0;
				}
				//bfs
				if(x >= 0 && x < M && y >= 0 && y < N &&maze[x][y] == 0 && visit[x][y] == 0){
					Node newNode = new Node(x, y, head.x, head.y, head.step + 1);
					queue.offer(newNode);
				}
	
			}
		}
		return -1;
	}	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BFS bfs = new BFS();
		if(bfs.bfs() < 0){
			System.out.println("Fail! Maybe no solution");
		}
		
	}

}

遞歸法:

用一個二維數組表示迷宮,0表示通路,1表示圍牆,給定入口和出口,尋找所有可能的通路。例如:


1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 1 1 1 1 1 1 1 1
1 1 1 0 1 1 0 0 0 0 1 1
1 1 1 0 1 1 0 1 1 0 1 1
1 1 1 0 0 0 0 1 1 0 1 1
1 1 1 0 1 1 0 1 1 0 1 1
1 1 1 0 0 0 0 1 1 0 1 1
1 1 1 1 1 1 0 1 1 0 1 1
1 1 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1
該迷宮較爲簡單,可看出有四條通路。可以利用遞歸的算法來找出所有通路。從入口開始作爲當前節點,判斷其上下左右四個節點是否可以通過,可以則選取其中一個作爲當前節點並標記爲已訪問,重複該步驟,用2標記通路,直至到達出口,打印該方案。實現代碼如下:

import java.util.*;
public class Maze {
	//初始化迷宮矩陣
	public static int[][] maze = 
		{
				{1,1,1,1,1,1,1,1,1,1,1,1},
				{1,0,0,0,1,1,1,1,1,1,1,1},
				{1,1,1,0,1,1,0,0,0,0,1,1},
				{1,1,1,0,1,1,0,1,1,0,1,1},
				{1,1,1,0,0,0,0,1,1,0,1,1},
				{1,1,1,0,1,1,0,1,1,0,1,1},
				{1,1,1,0,0,0,0,1,1,0,1,1},
				{1,1,1,1,1,1,0,1,1,0,1,1},
				{1,1,0,0,0,0,0,0,0,0,0,1},
				{1,1,1,1,1,1,1,1,1,1,1,1}
		};
	public static int bx = 1, by = 1, ex = 8, ey = 10;//入口、出口的行列下標
	public static int count = 0;//記錄方案的個數
	public static int[][] state = new int[maze.length][maze[0].length];//記錄節點是否被訪問,0表示未,1表示已
	public static void main(String[] args){		
		for(int i=0; i<state.length; i++){Arrays.fill(state[i],0);}
		maze[bx][by] = 2;
		move(bx,by);
	}
	public static void move(int i, int j){
		maze[i][j] = 2;//用2標記該節點,表示選擇該節點作爲路徑節點之一
		state[i][j] = 1;//用1表示該節點已被訪問,避免出現環路
		if(i==ex&&j==ey){
			count++;
			System.out.println("方案"+count+":");
			for(int k=0;k<maze.length;k++){//打印方案
				for(int l=0;l<maze[k].length;l++){
					System.out.print(maze[k][l]+" ");
				}
				System.out.println();
			}			
		}
		else{//判斷上下左右可通節點
			if(maze[i][j+1]==0&&state[i][j+1]==0){
				move(i,j+1);
			}
			if(maze[i+1][j]==0&&state[i+1][j]==0){
				move(i+1,j);
			}
			if(maze[i-1][j]==0&&state[i-1][j]==0){
				move(i-1,j);
			}
			if(maze[i][j-1]==0&&state[i][j-1]==0){
				move(i,j-1);
			}
		}
		maze[i][j] = 0;
		state[i][j] = 0;
	}
}

以一個M×N的長方陣表示迷宮,0和1分別表示迷宮中的通路和障礙。設計程序,對任意設定的迷宮,求出從入口到出口的所有通路。

    下面我們來詳細講一下迷宮問題的回溯算法。

    該圖是一個迷宮的圖。1代表是牆不能走,0是可以走的路線。只能往上下左右走,直到從左上角到右下角出口。

    做法是用一個二維數組來定義迷宮的初始狀態,然後從左上角開始,不停的去試探所有可行的路線,碰到1就結束本次路徑,然後探索其他的方向,當然我們要標記一下已經走的路線,不能反覆的在兩個可行的格子之間來回走。直到走到出口爲止,算找到了一個正確路徑。

    程序如下,具體做法看註釋即可。


回朔法:

package huisu;

/**
 * Created by wolf on 2016/3/21.
 */
public class MiGong {
    /**
     * 定義迷宮數組
     */
    private int[][] array = {
            {0, 0, 1, 0, 0, 0, 1, 0},
            {0, 0, 1, 0, 0, 0, 1, 0},
            {0, 0, 1, 0, 1, 1, 0, 1},
            {0, 1, 1, 1, 0, 0, 1, 0},
            {0, 0, 0, 1, 0, 0, 0, 0},
            {0, 1, 0, 0, 0, 1, 0, 1},
            {0, 1, 1, 1, 1, 0, 0, 1},
            {1, 1, 0, 0, 0, 1, 0, 1},
            {1, 1, 0, 0, 0, 0, 0, 0}

    };
    private int maxLine = 8;
    private int maxRow = 9;

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
        new MiGong().check(0, 0);
        System.out.println(System.currentTimeMillis());
    }

    private void check(int i, int j) {
        //如果到達右下角出口
        if (i == maxRow - 1 && j == maxLine - 1) {
            print();
            return;
        }

        //向右走
        if (canMove(i, j, i, j + 1)) {
            array[i][j] = 5;
            check(i, j + 1);
            array[i][j] = 0;
        }
        //向左走
        if (canMove(i, j, i, j - 1)) {
            array[i][j] = 5;
            check(i, j - 1);
            array[i][j] = 0;
        }
        //向下走
        if (canMove(i, j, i + 1, j)) {
            array[i][j] = 5;
            check(i + 1, j);
            array[i][j] = 0;
        }
        //向上走
        if (canMove(i, j, i - 1, j)) {
            array[i][j] = 5;
            check(i - 1, j);
            array[i][j] = 0;
        }
    }

    private boolean canMove(int i, int j, int targetI, int targetJ) {
//        System.out.println("從第" + (i + 1) + "行第" + (j + 1) + "列,走到第" + (targetI + 1) + "行第" + (targetJ + 1) + "列");
        if (targetI < 0 || targetJ < 0 || targetI >= maxRow || targetJ >= maxLine) {
//            System.out.println("到達最左邊或最右邊,失敗了");
            return false;
        }
        if (array[targetI][targetJ] == 1) {
//            System.out.println("目標是牆,失敗了");
            return false;
        }
        //避免在兩個空格間來回走
        if (array[targetI][targetJ] == 5) {
//            System.out.println("來回走,失敗了");
            return false;
        }

        return true;
    }

    private void print() {
        System.out.println("得到一個解:");
        for (int i = 0; i < maxRow; i++) {
            for (int j = 0; j < maxLine; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }
}

請輸入迷宮的行數

3

請輸入迷宮的列數

3

請輸入3行3列的迷宮

0 1 1

0 0 1

1 0 0

有路徑

路徑如下:

# 1 1

# # 1

1 # #

-----------------------------------------------------------

請輸入迷宮的行數
9
請輸入迷宮的列數
8
請輸入9行8列的迷宮
0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0
0 0 1 0 1 1 0 1
0 1 1 1 0 0 1 0
0 0 0 1 0 0 0 0
0 1 0 0 0 1 0 1
0 1 1 1 1 0 0 1
1 1 0 0 0 1 0 1
1 1 0 0 0 0 0 0
有路徑
路徑如下:
# # 1 0 0 0 1 0
0 # 1 0 0 0 1 0
# # 1 0 1 1 0 1
# 1 1 1 0 0 1 0
# # # 1 # # # 0
0 1 # # # 1 # 1
0 1 1 1 1 0 # 1
1 1 0 0 0 1 # 1
1 1 0 0 0 0 # #

本人誠知自己算法水平太次,希望得到大家指點。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章