深度优先的迷宫图算法。
N年前的老问题了。
10分不值得做。
Ⅱ JAVA走迷宫问题-怎么使迷宫一定走通
可以逆向思考,怎么说呢,就是说。
假设现在咱们就在迷宫的出口,那么你往回走(这个往回走,就是随机产生的,可以任意一个方向),最后到达入口,那么这么一个路线就一定可以走的通 呀。。。
Ⅲ java迷宫路径总条数问题
int[][] data是你的迷宫数组,返回值是路径总条数,不需要递归
public int findWayCount(int[][] data) {
int[][] way = new int[data.length][];
for (int m = 0; m < data.length; m++) {
way[m] = new int[data[m].length];
for (int n = 0; n < data[m].length; n++) {
if (data[m][n] == 0) {
way[m][n] = 0;
} else if (m == 0 && n == 0) {
way[m][n] = data[0][0];
} else if (m == 0) {
way[m][n] = way[m][n - 1];
} else if (n == 0) {
way[m][n] = way[m - 1][n];
} else {
way[m][n] = way[m][n - 1] + way[m - 1][n];
}
}
}
Ⅳ 急需一java高手帮忙写一迷宫程序
给你代码,你给出的那两个类,不能满足,我的需要,我就没有使用。
你看一下吧。
----------------------------------------
package stackpackage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Maze {
// 上
private static Point directionTop = new Point(-1, 0);
// 下
private static Point directionBottom = new Point(1, 0);
// 左
private static Point directionLeft = new Point(0, -1);
// 右
private static Point directionRight = new Point(0, 1);
private static Point[] directions = { directionTop, directionRight,
directionBottom, directionLeft };
private static boolean isStop = false;
private static int row = 0;
private static int col = 0;
private static Point startPoint = new Point();
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
int rowIndex = 1;
int[][] maze = null;
while (br.ready()) {
String line = br.readLine();
Scanner sc = new Scanner(line);
if (rowIndex == 1) {
row = sc.nextInt();
col = sc.nextInt();
maze = new int[row][col];
} else {
if (rowIndex < row + 2) {
for (int i = 0; i < col; i++) {
maze[rowIndex - 2][i] = sc.nextInt();
}
} else {
startPoint.x = sc.nextInt();
startPoint.y = sc.nextInt();
}
}
rowIndex++;
}
List<Point> route = new ArrayList<Point>();
route.add(startPoint);
findNext(startPoint);
puzzle(maze, startPoint, route);
System.out.println(route);
}
private static void puzzle(int[][] maze, Point p, List<Point> route) {
if (isStop) {
return;
}
Point[] nextDirections = p.nextDirections;
for (int i = 0; i < nextDirections.length; i++) {
if (isStop) {
return;
}
Point direction = nextDirections[i];
Point newP = new Point(p.x + direction.x, p.y + direction.y);
if (newP.isEffective() && maze[newP.x][newP.y] == 0
&& !route.contains(newP)) {
newP.before = p;
findNext(newP);
route.add(newP);
if (isExit(newP)) {
isStop = true;
break;
}
puzzle(maze, newP, route);
}
}
if (isStop) {
return;
}
route.remove(route.size() - 1);
}
private static void findNext(Point p) {
int index = 0;
Point[] nextDirections = new Point[3];
for (int i = 0; i < nextDirections.length; i++) {
nextDirections[i] = new Point(0, 0);
}
for (int i = 0; i < directions.length; i++) {
Point direction = directions[i];
Point newP = new Point(p.x + direction.x, p.y + direction.y);
if (newP.isEffective() && !newP.equals(p.before) && newP.x < row
&& newP.y < col) {
nextDirections[index++] = direction;
}
}
p.nextDirections = nextDirections;
}
private static boolean isExit(Point p) {
if (startPoint.equals(p)) {
return false;
}
for (int i = 0; i < directions.length; i++) {
Point direction = directions[i];
Point newP = new Point(p.x + direction.x, p.y + direction.y);
if (!newP.equals(p.before)
&& (newP.x >= row || newP.y >= col || newP.x < 0 || newP.y < 0)) {
return true;
}
}
return false;
}
}
class Point {
int x = 0;
int y = 0;
Point[] nextDirections = null;
Point before = null;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "<" + x + "," + y + ">";
}
public boolean isEffective() {
return x >= 0 && y >= 0;
}
public boolean equals(Object obj) {
return equals((Point) obj);
}
public boolean equals(Point p) {
if (p == null) {
return false;
}
return this.x == p.x && this.y == p.y;
}
}
Ⅳ 急求大佬帮忙写一下java程序
递归的话就是深度优先搜索(可以理解成不撞南墙不回头,撞了墙就原路返回)可以加上剪枝(就是做标记,如果之前某一次走过但不通的路下次再走到就不用走了)
用栈的话应该是广度优先搜索(大概就是分裂无数个你,每次向所有方向走一步),不过广搜要用队列实现,用栈本质还是深搜了
具体算法可以搜网络
Ⅵ Java迷宫算法问题(用栈实现)有算法简述
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.HashSet;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Scanner;
publicclassTest{
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
Scannerinput=newScanner(newFile("Maze2tong.txt"));
introw=0;
char[][]Mazemap=newchar[12][58];
while(input.hasNext()){
Stringline=input.nextLine();
for(intcolumn=0;column<=line.length()-1;column++){
charc=line.charAt(column);
Mazemap[row][column]=c;
}
row++;
}
for(inti=0;i<12;i++){
for(intj=0;j<58;j++){
System.out.print(Mazemap[i][j]);
}
System.out.print(" ");
}
LinkedList<TwoTuple<Integer,Integer>>trace=newLinkedList<TwoTuple<Integer,Integer>>();
System.out.println(maze(Mazemap,trace));
System.out.println(trace);
}
publicstaticbooleanmaze(char[][]maze,
List<TwoTuple<Integer,Integer>>trace){
LinkedList<TwoTuple<Integer,Integer>>path=newLinkedList<TwoTuple<Integer,Integer>>();
HashSet<TwoTuple<Integer,Integer>>traverse=newHashSet<TwoTuple<Integer,Integer>>();
for(inti=0;i<maze.length;i++){
for(intj=0;j<maze[i].length;j++){
if(maze[i][j]=='S'){
path.add(newTwoTuple<Integer,Integer>(i,j));
}
}
}
while(!path.isEmpty()){
TwoTuple<Integer,Integer>temp=path.pop();
if(traverse.contains(temp)){
continue;
}elseif(maze[temp.first][temp.second]=='F'){
trace.add(temp);
returntrue;
}elseif(!traverse.contains(temp)){
if(temp.second+1<maze[temp.first].length
&&maze[temp.first][temp.second+1]!='W')
path.add(newTwoTuple<Integer,Integer>(temp.first,
temp.second+1));
if(temp.second-1>0
&&maze[temp.first][temp.second-1]!='W')
path.add(newTwoTuple<Integer,Integer>(temp.first,
temp.second-1));
if(temp.first+1<maze.length
&&maze[temp.first+1][temp.second]!='W')
path.add(newTwoTuple<Integer,Integer>(temp.first+1,
temp.second));
if(temp.first-1>0
&&maze[temp.first-1][temp.second]!='W')
path.add(newTwoTuple<Integer,Integer>(temp.first-1,
temp.second));
traverse.add(temp);
trace.add(temp);
}
}
trace.clear();
returnfalse;
}
}
classTwoTuple<A,B>{
publicfinalAfirst;
publicfinalBsecond;
publicTwoTuple(Aa,Bb){
first=a;
second=b;
}
@Override
publicinthashCode(){
returnfirst.hashCode()+second.hashCode();
}
@Override
publicbooleanequals(Objectobj){
if(!(objinstanceofTwoTuple)){
}
returnobjinstanceofTwoTuple&&first.equals(((TwoTuple)obj).first)
&&second.equals(((TwoTuple)obj).second);
}
publicStringtoString(){
return"("+first+","+second+")";
}
}///:-
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.LinkedList;
importjava.util.Scanner;
classMyPoint
{
publicbooleanvisited=false;
publicintparentRow=-1;
publicintparentColumn=-1;
publicfinalcharcontent;
publicintx;
publicinty;
publicMyPoint(charc,intx,inty)
{
this.content=c;
this.x=x;
this.y=y;
}
}
publicclassMaze
{
publicstaticMyPoint[][]getMazeArray(){
Scannerinput=null;
MyPoint[][]mazemap=newMyPoint[12][58];
try{
input=newScanner(newFile("Maze2tong.txt"));
introw=0;
while(input.hasNext()){
Stringline=input.nextLine();
for(intcolumn=0;column<=line.length()-1;column++){
charc=line.charAt(column);
MyPointpoint=newMyPoint(c,row,column);
mazemap[row][column]=point;
}
row++;
}
input.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
returnmazemap;
}
publicstaticbooleantomRun(MyPoint[][]maze,MyPointend)
{
intx=maze.length;
inty=maze[0].length;
LinkedList<MyPoint>stack=newLinkedList<MyPoint>();
for(inti=0;i<maze.length;i++){
for(intj=0;j<maze[i].length;j++){
if(maze[i][j].content=='S'){
stack.push(maze[i][j]);
maze[i][j].visited=true;
}
}
}
booleanresult=false;
while(!stack.isEmpty())
{
MyPointt=stack.pop();
//System.out.println("poppoint:"+t.x+""+t.y+"value:"+maze[t.x][t.y]);
if(t.content=='F')
{
result=true;
end.x=t.x;
end.y=t.y;
break;
}
if(t.x-1>0&&maze[t.x-1][t.y].visited==false&&maze[t.x-1][t.y].content!='W')
{
stack.push(maze[t.x-1][t.y]);
maze[t.x-1][t.y].parentRow=t.x;
maze[t.x-1][t.y].parentColumn=t.y;
maze[t.x-1][t.y].visited=true;
}
if(t.x+1<x&&maze[t.x+1][t.y].visited==false&&maze[t.x+1][t.y].content!='W')
{
stack.push(maze[t.x+1][t.y]);
maze[t.x+1][t.y].parentRow=t.x;
maze[t.x+1][t.y].parentColumn=t.y;
maze[t.x+1][t.y].visited=true;
}
if(t.y-1>0&&maze[t.x][t.y-1].visited==false&&maze[t.x][t.y-1].content!='W')
{
stack.push(maze[t.x][t.y-1]);
maze[t.x][t.y-1].parentRow=t.x;
maze[t.x][t.y-1].parentColumn=t.y;
maze[t.x][t.y-1].visited=true;
}
if(t.y+1<y&&maze[t.x][t.y+1].visited==false&&maze[t.x][t.y+1].content!='W')
{
stack.push(maze[t.x][t.y+1]);
maze[t.x][t.y+1].parentRow=t.x;
maze[t.x][t.y+1].parentColumn=t.y;
maze[t.x][t.y+1].visited=true;
}
}
returnresult;
}
publicstaticvoidshow(intx,inty,MyPoint[][]visited)
{
if(visited[x][y].parentRow==-1)
{
System.out.println("["+x+","+y+"]");
return;
}
show(visited[x][y].parentRow,visited[x][y].parentColumn,visited);
System.out.println("->"+"["+x+","+y+"]");
}
publicstaticvoidmain(String[]args)
{
MyPoint[][]maze=getMazeArray();
MyPointpoint=newMyPoint('c',1,1);
if(tomRun(maze,point))
{
System.out.println("逃生路径如下:");
show(point.x,point.y,maze);
}
else
System.out.println("无法走出迷宫!");
}
}
Ⅶ 用java语言控制小机器人走迷宫的算法
我昨天刚写了个走迷宫的界面(一个初始小球,一个目标小球,随机在界面种生成障碍(迷宫图),然后初始小球移动到目标小球那),不知道是否跟你的想法一样。用的是回溯法(目前我只知道这个算法走迷宫),你可以查下。PS:我电脑没联网不能把代码给你…QQ254774042。
Ⅷ 请帮忙用数据结构(java版)的知识解决这道迷宫问题的程序代码。
我这是用c写的。你可以看看,希望能帮助到你。
#include"stdlib.h"
#include"stdio.h"
#define N 50
#define M 50
int X;
int maze[N+2][M+2];
struct point{
int row,col,predecessor;
}queue[512];
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;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&maze[i][j]);
}
void zidong_maze(int m,int n){
int i,j;
printf("\n迷宫生成中……\n\n");
system("pause");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
maze[i][j]=rand()%2;
//由于rand()产生的随机数是从0到RAND_MAX
//RAND_MAX是定义在stdlib.h中的,其值至少为32767)
//要产生从X到Y的数,只需要这样写:k=rand()%(Y-X+1)+X;
}
void print_maze(int m,int n){
int i,j;
printf("\n迷宫生成结果如下:\n\n");
printf("迷宫入口\n");
printf("↓");
for(i=0;i<m;i++)
{printf("\n");
for(j=0;j<n;j++)
{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");
for(i=0;i<m;i++)
{ printf("\n");
for(j=0;j<n;j++)
{if(maze[i][j]==0||maze[i][j]==2) printf("□");
if(maze[i][j]==1) printf("■");
if(maze[i][j]==3) printf("☆");
}
}
}
void enqueue(struct point p)
{ queue[tail]=p;
tail++;
}
struct point dequeue()
{ head++;
return queue[head-1];
}
int is_empty()
{ return head==tail;
}
void visit(int row,int col,int maze[52][52])
{ struct point visit_point={row,col,head-1};
maze[row][col]=2;
enqueue(visit_point);
}
int mgpath(int maze[52][52],int m,int n)
{ 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;}
maze[p.row][p.col]=2;
enqueue(p);
while(!is_empty())
{p=dequeue();
if((p.row==m-1)&&(p.col==n-1)) break;
if((p.col+1<n)&&(maze[p.row][p.col+1]==0)) visit(p.row,p.col+1,maze);
if((p.row+1<m)&&(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-1&&p.col==n-1)
{printf("\n==================================================================\n");
printf("迷宫路径为:\n");
printf("(%d,%d)\n",p.row,p.col);
maze[p.row][p.col]=3;
while(p.predecessor!=-1)
{p=queue[p.predecessor];
printf("(%d,%d)\n",p.row,p.col);
maze[p.row][p.col]=3;
}
}
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(" 设计者:尹旭 林静波(信息2班)\n");
printf("********************************************************************************\n");
printf(" 手动生成迷宫 请按:1\n");
printf(" 自动生成迷宫 请按:2\n");
printf(" 退出 请按:3\n\n");
printf("********************************************************************************\n");
printf("\n");
printf("请选择你的操作:\n");
scanf("%d",&i);
switch(i)
{case 1:printf("\n请输入行数:");
scanf("%d",&m);
printf("\n");
printf("请输入列数:");
scanf("%d",&n);
while((m<=0||m>50)||(n<=0||n>50))
{ printf("\n抱歉,你输入的行列数超出预设范围(0-50,0-50),请重新输入:\n\n");
printf("请输入行数:");
scanf("%d",&m);
printf("\n");
printf("请输入列数:");
scanf("%d",&n);
}
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;
case 2:printf("\n请输入行数:");
scanf("%d",&m);
printf("\n");
printf("请输入列数:");
scanf("%d",&n);
while((m<=0||m>50)||(n<=0||n>50))
{printf("\n抱歉,你输入的行列数超出预设范围(0-50,0-50),请重新输入:\n\n");
printf("请输入行数:");
scanf("%d",&m);
printf("\n");
printf("请输入列数:");
scanf("%d",&n);
}
zidong_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;
case 3:cycle=(-1);
break;
default:printf("\n");
printf("你的输入有误!\n");
printf("\nPress Enter Contiue!\n");
getchar();
while(getchar()!='\n');break;
}
}
}
Ⅸ 帮忙给个迷宫问题的JAVA程序,最好是用VC..粘的也好,只要可以运行就好..
import java.io.*;
import java.util.Stack;
class MazeCell {
int x, y;
MazeCell() {
}
MazeCell(int i, int j) {
x = i; y = j;
}
boolean equals(MazeCell cell) {
return x == cell.x && y == cell.y;
}
}
class Maze {
int rows = 0, cols = 0;
char[][] store;
MazeCell currentCell, exitCell = new MazeCell(), entryCell = new MazeCell();
final char exitMarker = 'e', entryMarker = 'm', visited = '.';
final char passage = '0', wall = '1';
Stack mazeStack = new Stack();
Maze() {
int row = 0, col = 0;
Stack mazeRows = new Stack();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
String str;
System.out.println("Enter a rectangular maze using the following "
+ "characters:\nm - entry\ne - exit\n1 - wall\n0 - passage\n"
+ "Enter one line at at time; end with Ctrl-z (PC) or Ctrl-D (Unix):");
try {
str = buffer.readLine();
while (str != null) {
row++;
cols = str.length();
str = "1" + str + "1"; // put 1s in the borderline cells;
mazeRows.push(str);
if (str.indexOf(exitMarker) != -1) {
exitCell.x = row;
exitCell.y = str.indexOf(exitMarker);
}
if (str.indexOf(entryMarker) != -1) {
entryCell.x = row;
entryCell.y = str.indexOf(entryMarker);
}
str = buffer.readLine();
}
} catch(IOException eof) {
}
rows = row;
store = new char[rows+2][]; // create a 1D array of char arrays;
store[0] = new char[cols+2]; // a borderline row;
for ( ; !mazeRows.isEmpty(); row--)
store[row] = ((String) mazeRows.pop()).toCharArray();
store[rows+1] = new char[cols+2]; // another borderline row;
for (col = 0; col <= cols+1; col++) {
store[0][col] = wall; // fill the borderline rows with 1s;
store[rows+1][col] = wall;
}
}
void display(PrintStream out) {
for (int row = 0; row <= rows+1; row++)
out.println(store[row]);
out.println();
}
void pushUnvisited(int row, int col) {
if (store[row][col] == passage || store[row][col] == exitMarker)
mazeStack.push(new MazeCell(row,col));
}
void exitMaze(PrintStream out) {
int row = 0, col = 0;
currentCell = entryCell;
out.println();
while (!currentCell.equals(exitCell)) {
row = currentCell.x;
col = currentCell.y;
display(System.out); // print a snapshot;
if (!currentCell.equals(entryCell))
store[row][col] = visited;
pushUnvisited(row-1,col);
pushUnvisited(row+1,col);
pushUnvisited(row,col-1);
pushUnvisited(row,col+1);
if (mazeStack.isEmpty()) {
display(out);
out.println("Failure");
return;
}
else currentCell = (MazeCell) mazeStack.pop();
}
display(out);
out.println("Success");
}
static public void main (String args[]) {
(new Maze()).exitMaze(System.out);
}
}
试一下这个,是不是你想要的……
___________________________________________________________________________________________________________________________
html代码?你是说你要做一个java applet的网页迷宫小游戏??
Ⅹ 求用java语言寻找走出迷宫路线的算法
首先给定一个初始坐标,然后构建一个容器保存坐标值,之后进行迭代,横坐标+1,或者纵坐标+1,这个顺寻自己定义(四个方向),经过的“路径”保存在那个容器中,如果遇到死角,以此往回迭代,在容器中将遇到死角的那个坐标删除。最后找到自己定义的那个迷宫出口坐标。