# 迷宫问题解法汇总

1401人阅读 评论(0)

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

# java写的回溯法求迷宫问题

[实验目的]

[实验内容及要求]

（1）    根据二维数组，输出迷宫的图形。

（2）    探索迷宫的四个方向：RIGHT为向右，DOWN向下，LEFT向左，UP向上，输出从入口到出口的行走路径。

[测试数据]

 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.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);
Stack<BFS.Node> stack = new Stack<BFS.Node>();
queue.offer(node);
//visit[0][0] = 1;
while(!queue.isEmpty()){
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){
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");
}

}

}

 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

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;
}
}

下面我们来详细讲一下迷宫问题的回溯算法。

该图是一个迷宫的图。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

0 1 1

0 0 1

1 0 0

# 1 1

# # 1

1 # #

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

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 # #

0
1

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：274177次
• 积分：4677
• 等级：
• 排名：第6221名
• 原创：193篇
• 转载：163篇
• 译文：4篇
• 评论：15条
我的编码目标