package 走迷宫;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
// 迷宫
public class Maze extends JFrame implements ActionListener {
private JPanel panel;
private JPanel northPanel;
private JPanel centerPanel;
private MazeGrid grid[][];
private JButton restart;
private JButton dostart;
private int rows;// rows 和cols目前暂定只能是奇数
private int cols;
private ListString willVisit;
private ListString visited;
private LinkedListString comed;
private long startTime;
private long endTime;
public Maze() {
willVisit = new ArrayListString();
visited = new ArrayListString();
comed = new LinkedListString();
init();
this.setTitle("回溯法--走迷宫");
this.add(panel);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init() {
panel = new JPanel();
northPanel = new JPanel();
centerPanel = new JPanel();
panel.setLayout(new BorderLayout());
restart = new JButton("重新生成迷宫");
dostart = new JButton("开始走迷宫");
grid = new MazeGrid[rows][cols];
centerPanel.setLayout(new GridLayout(rows, cols, 1, 1));
centerPanel.setBackground(new Color(0, 0, 0));
northPanel.add(restart);
northPanel.add(dostart);
dostart.addActionListener(this);
restart.addActionListener(this);
for (int i = 0; i grid.length; i++)
for (int j = 0; j grid[i].length; j++) {
else
grid[0][0].setVisited(true);
grid[0][0].setPersonCome(true);
grid[0][0].setStart(true);
visited.add("0#0");
grid[rows - 1][cols - 1].setEnd(true);
grid = createMap(grid, 0, 0);
grid[i][j].repaint();
centerPanel.add(grid[i][j]);
panel.add(northPanel, BorderLayout.NORTH);
panel.add(centerPanel, BorderLayout.CENTER);
/**
* 生成迷宫
*
* @param mazeGrid
* @param x
* @param y
* @return
*/
public MazeGrid[][] createMap(MazeGrid mazeGrid[][], int x, int y) {
int visitX = 0;
int visitY = 0;
if (!willVisit.isEmpty()) {
int visit = (int) (Math.random() * willVisit.size());
String id = willVisit.get(visit);
visitX = Integer.parseInt(id.split("#")[0]);
visitY = Integer.parseInt(id.split("#")[1]);
mazeGrid[visitX][visitY].setVisited(true);
if (!visited.contains(id)) {// 将这个点加到已访问中去
visited.add(id);
willVisit.clear();
createMap(mazeGrid, visitX, visitY);
} else {
if (!visited.isEmpty()) {
String id = visited.remove(visited.size() - 1);// 取出最后一个元素
return mazeGrid;
* 走迷宫
public String goMaze(MazeGrid mazeGrid[][], int x, int y) {
int comeX = 0;
int comeY = 0;
// left
if (x - 1 = 0) {
if (mazeGrid[x - 1][y].isMark()) {
if (!comed.contains((x - 1) + "#" + y))
willVisit.add((x - 1) + "#" + y);
// right
if (x + 1 cols) {
if (mazeGrid[x + 1][y].isMark()) {
if (!comed.contains((x + 1) + "#" + y))
willVisit.add((x + 1) + "#" + y);
// up
if (y - 1 = 0) {
if (mazeGrid[x][y - 1].isMark()) {
if (!comed.contains(x + "#" + (y - 1)))
willVisit.add(x + "#" + (y - 1));
// down
if (y + 1 rows) {
if (mazeGrid[x][y + 1].isMark()) {
if (!comed.contains(x + "#" + (y + 1)))
willVisit.add(x + "#" + (y + 1));
comeX = Integer.parseInt(id.split("#")[0]);
comeY = Integer.parseInt(id.split("#")[1]);
mazeGrid[x][y].setPersonCome(false);
mazeGrid[comeX][comeY].setPersonCome(true);
mazeGrid[x][y].repaint();
mazeGrid[comeX][comeY].repaint();
comed.add(x + "#" + y);
if (!comed.isEmpty()) {
String id = comed.removeLast();
comed.addFirst(x + "#" + y);
return comeX + "#" + comeY;
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("重新生成迷宫")) {
refreshMap(grid);
} else if (e.getActionCommand().equals("开始走迷宫")) {
startTime = System.currentTimeMillis();
dostart.setVisible(false);
restart.setText("禁止刷新");
int delay = 1000;
java.util.Timer timer = new java.util.Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (grid[rows - 1][cols - 1].isPersonCome()) {
endTime = System.currentTimeMillis();
JOptionPane.showMessageDialog(null, "已经走出迷宫,耗时"
+ (endTime - startTime) / 1000 + "秒", "消息提示",
JOptionPane.ERROR_MESSAGE);
this.cancel();
restart.setText("重新生成迷宫");
String id = goMaze(grid, comeX, comeY);
}, delay, period);
* 刷新地图
public void refreshMap(MazeGrid mazeGrid[][]) {
comeX = 0;
comeY = 0;
visited.clear();
comed.clear();
this.remove(panel);
public static void main(String args[]) {
long start = System.currentTimeMillis();
new Maze();
long end = System.currentTimeMillis();
System.out.println("使用ArrayList生成迷宫耗时:" + (end - start) + "毫秒");
我这是用c写的.你可以看看,希望能帮助到你.
#include"stdlib.h"
#include"stdio.h"
int X;
struct point{
int row,col,predecessor;
int head=0,tail=0;
void shoudong_maze(int m,int n){
int i,j;
printf("\n\n");
printf("请按行输入迷宫,0表示通路,1表示障碍:\n\n");
for(i=0;im;i++)
for(j=0;jn;j++)
scanf("%d",maze[i][j]);
void zidong_maze(int m,int n){
printf("\n迷宫生成中......\n\n");
system("pause");
//由于rand()产生的随机数是从0到RAND_MAX
//要产生从X到Y的数,只需要这样写:k=rand()%(Y-X+1)+X;
void print_maze(int m,int n){
printf("\n迷宫生成结果如下:\n\n");
printf("迷宫入口\n");
printf("↓");
{printf("\n");
{if(maze[i][j]==0) printf("□");
if(maze[i][j]==1) printf("■");}
printf("→迷宫出口\n");
void result_maze(int m,int n)
{ int i,j;
printf("迷宫通路(用☆表示)如下所示:\n\t");
{ printf("\n");
if(maze[i][j]==1) printf("■");
void enqueue(struct point p)
{ queue[tail]=p;
tail++;
struct point dequeue()
{ head++;
return queue[head-1];
int is_empty()
{ return head==tail;
{ struct point visit_point={row,col,head-1};
enqueue(visit_point);
{ X=1;
struct point p={0,0,-1};
if(maze[p.row][p.col]==1)
{ printf("\n===============================================\n");
printf("此迷宫无解\n\n");X=0;return 0;}
enqueue(p);
while(!is_empty())
{p=dequeue();
if((p.row==m-1)(p.col==n-1)) break;
if((p.col+1n)(maze[p.row][p.col+1]==0)) visit(p.row,p.col+1,maze);
if((p.row+1m)(maze[p.row+1][p.col]==0)) visit(p.row+1,p.col,maze);
if((p.col-1=0)(maze[p.row][p.col-1]==0)) visit(p.row,p.col-1,maze);
if((p.row-1=0)(maze[p.row-1][p.col]==0)) visit(p.row-1,p.col,maze);
if(p.row==m-1p.col==n-1)
{printf("\n==================================================================\n");
printf("迷宫路径为:\n");
printf("(%d,%d)\n",p.row,p.col);
while(p.predecessor!=-1)
{p=queue[p.predecessor];
else {printf("\n=============================================================\n");
printf("此迷宫无解!\n\n");X=0;}
return 0;
int main()
{int i,m,n,cycle=0;
while(cycle!=(-1))
{
printf("********************************************************************************\n");
printf(" ☆欢迎进入迷宫求解系统☆\n");
printf(" 手动生成迷宫 请按:1\n");
printf("\n");
printf("请选择你的操作:\n");
scanf("%d",i);
switch(i)
{case 1:printf("\n请输入行数:");
scanf("%d",m);
printf("请输入列数:");
scanf("%d",n);
printf("请输入行数:");
shoudong_maze(m,n);
print_maze(m,n);
mgpath(maze,m,n);
if(X!=0)
result_maze(m,n);
printf("\n\nPress Enter Contiue!\n");
getchar();
while(getchar()!='\n');
break;
zidong_maze(m,n);
printf("\n\nPress Enter Contiue!\n");getchar();while(getchar()!='\n');break;
default:printf("\n");
printf("你的输入有误!\n");
printf("\nPress Enter Contiue!\n");
while(getchar()!='\n');break;
System.out.println("The Maza route is ("+Loci+","+Locj+")");就打印出程序所走路径的坐标了.
//直译了哦,只有片面的代码,只能靠推测,其他你自己补充下:
//这个主要是对一个图像控件设置了键盘侦听事件,按下键盘时候对其进行坐标移位操作
//必须知道:ImageView图像控件,显示图片或者其他;num是一个二位数组,这里可以理解成矩阵地图;
public?void?control(int[][]?num,?ImageView?iv)?{
//对控件设置键盘侦听,
iv.setOnKeyPressed(e?-?{
//设置一个变量,从下面使用看,这个应该是一个图像步进单位
//以下为:try?catch封装的键盘四向按键判断
try?{
//字面意义推测:row应该是行,col应该是列,这是用二维数组画了一个矩阵地图,0不能走,1可以走;
//如果键盘按下的键是s,并且"行+1"小于地图中的行的个数,并且:地图[row+1行][col列]的值不等于0
if?(e.getCode()?==?KeyCode.S?row?+?1?num.length?num[row?+?1][col]?!=?0)?{
//就设置图像y坐标(在原有坐标的基础上进行一个步进单位的叠加)
iv.setY(iv.getY()?+?m);
//行递增1:row=row+1;
row++;
//其实这里与下面与上面都是一个道理,仅仅判断的条件与按键不同罢了
if?(e.getCode()?==?KeyCode.W?row?-?1?=?0?num[row?-?1][col]?!=?0)?{
iv.setY(iv.getY()?-?m);
//行递减1
row--;
//同上
if?(e.getCode()?==?KeyCode.A?col?-?1?=?0?num[row][col?-?1]?!=?0)?{
iv.setX(iv.getX()?-?m);
//列递减1
col--;
if?(e.getCode()?==?KeyCode.D?col?+?1?num[0].length?num[row][col?+?1]?!=?0)?{
iv.setX(iv.getX()?+?m);
//列递增1
col++;
}catch?(Exception?n)?{}
//如果行等于地图"行"的最大的索引值,并且列等于第一行数组的最大索引值
if?(row?==?num.length?-?1?col?==?num[0].length?-?1)?{
//就调用win函数;
win();
});
不是不想帮你.像这种问题 需要去专业性网站去问.并且 分数一定要高.
比如 这个论坛里 高手都往这里走. 再高高的高手只会在自己的领域.不会上网上论坛.嘿嘿
public class Maze { private int[][] maze = null;
private int[] xx = { 1, 0, -1, 0 };
private int[] yy = { 0, 1, 0, -1 };
private Queue queue = null; public Maze(int[][] maze) {
this.maze = maze;
queue = new Queue(maze.length * maze.length);
} public void go() {
Point outPt = new Point(maze.length - 1, maze[0].length - 1);
Point curPt = new Point(0, 0);
Node curNode = new Node(curPt, null);
queue.entryQ(curNode); while (!queue.isEmpty()) {
curNode = queue.outQ();
for (int i = 0; i xx.length; ++i) {
Point nextPt = new Point();
nextPt.x = (curNode.point).x + xx[i];
nextPt.y = (curNode.point).y + yy[i];
if (check(nextPt)) {
Node nextNode = new Node(nextPt, curNode);
queue.entryQ(nextNode);
if (nextPt.equals(outPt)) {
java.util.StackNode stack = new java.util.StackNode();
stack.push(nextNode);
while ((curNode = nextNode.previous) != null) {
nextNode = curNode;
stack.push(curNode);
System.out.println("A Path is:");
while (!stack.isEmpty()) {
curNode = stack.pop();
System.out.println(curNode.point);
return;
System.out.println("Non solution!");
} private boolean check(Point p) {
if (p.x 0 || p.x = maze.length || p.y 0 || p.y = maze[0].length) {
return false;
if (maze[p.x][p.y] != 0) {
return true;
} public static void main(String[] args) {
int[][] maze = {
{ 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, 0, 1, 0, 1, 1, 0, 1, 0, 0 }
};
new Maze(maze).go();
} private class Queue { Node[] array = null;
int size = 0;
int len = 0;
int head = 0;
int tail = 0; public Queue(int n) {
array = new Node[n + 1];
size = n + 1;
} public boolean entryQ(Node node) {
if (isFull()) {
tail = (tail + 1) % size;
array[tail] = node;
len++;
} public Node outQ() {
if (isEmpty()) {
return null;
head = (head + 1) % size;
len--;
return array[head];
} public boolean isEmpty() {
return (len == 0 || head == tail) ? true : false;
} public boolean isFull() {
return ((tail + 1) % size == head) ? true : false;
} private class Node { Point point = null;
Node previous = null; public Node() {
this(null,null);
} public Node(Point point, Node node) {
this.point = point;
this.previous = node;
} private class Point { int x = 0;
int y = 0; public Point() {
this(0, 0);
} public Point(int x, int y) {
this.x = x;
this.y = y;
} public boolean equals(Point p) {
return (x == p.x) (y == p.y);
} @Override
public String toString() {
return "(" + x + "," + y + ")";
以上就是土嘎嘎小编为大家整理的迷宫的java代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!