MakeMaze
虽然得了奖,
但自己java水平有限,
代码的质量不能保证,
有问题欢迎指正,
** 有不懂的地方可以留言 .**
import java.util.Stack;
import java.io.*;
/*
*生成随机生成一张迷宫地图,*为起点,#为终点
*运用的主要思想离散数学,无向图的遍历.
*应用于<大连交通大学课程设计大赛,迷宫程序的修改与改进>
*/
public class MakeMaze
{
int M,N;
char Maze[][];
MakeMaze ()
{
M=23;
N=49;
Maze=new char[M][N];
}
public void setSize(int m, int n)
{
M=m;
N=n;
}
int [] getUsability(int m,int n) //
{
int Flag[]=new int[9];
int i=0;
if((m-2)>=0&&Maze[m-2][n]!='0')
{
Flag[i]=m-2;
i++;
Flag[i]=n;
i++;
}
if((m+2)<M && Maze[m+2][n]!='0')
{
Flag[i]=m+2;
i++;
Flag[i]=n;
i++;
}
if((n-2)>=0&&Maze[m][n-2]!='0')
{
Flag[i]=m;
i++;
Flag[i]=n-2;
i++;
}
if((n+2)<N&&Maze[m][n+2]!='0')
{
Flag[i]=m;
i++;
Flag[i]=n+2;
i++;
}
Flag[8]=i/2;
return Flag;
}
public void writeFile(char maze[][])
{
try{
int i;
FileWriter one =new FileWriter("randommaze.data");
BufferedWriter two= new BufferedWriter (one);
for (i=0;i<maze.length;i++ )
{
two.write(String.valueOf(maze[i]));
two.newLine();
}
two.close();
one.close();
}
catch( IOException e){System.out.print(e);}
}
public void getEnterExit()
{
int i,j;
int start=(int)(Math.random()*4);
switch (start)
{
case 0:
i=(int)(M*Math.random());
j=0;
Maze[i][j]='*';
Maze[i][j+1]='0';
Maze[M-i-1][N-j-1]='#';
Maze[M-i-1][N-j-2]='0';
break;
case 1:
i=(int)(M*Math.random());
j=N-1;
Maze[i][j]='*';
Maze[i][j-1]='0';
Maze[M-i-1][N-j-1]='#';
Maze[M-i-1][N-j]='0';
break;
case 2:
i=0;
j=(int)(N*Math.random());
Maze[i][j]='*';
Maze[i+1][j]='0';
Maze[M-i-1][N-j-1]='#';
Maze[M-i-2][N-j-1]='0';
case 3:
i=M-1;
j=(int)(N*Math.random());
Maze[i][j]='*';
Maze[i-1][j]='0';
Maze[M-i-1][N-j-1]='#';
Maze[M-i][N-j-1]='0';
break;
}
}
public char[][] RandomMaze()
{
Stack V =new Stack();
int i=0,j=0;
int count[];
int flag=0;
int number=0;
for (i=0;i< M; i++)
{
for (j=0;j<N ;j++ )
{
if((i+j)%2==0&&j%2==0)
{
Maze[i][j]='a';
number++;
}
else
Maze[i][j]='1';
}
}
i=j=0;
while(number>0)
{
count=getUsability(i,j);
if(count[8]!=0)
{
flag=(int)(count[8]*Math.random())*2;
Maze[count[flag]][count[flag+1]]='0';
number--;
Maze[(count[flag]+i)/2][(count[flag+1]+j)/2]='0';
V.push(i);
V.push(j);
i=count[flag];
j=count[flag+1];
}
else if (!V.isEmpty())
{
j=(int)V.pop();
i=(int)V.pop();
}
}
getEnterExit();
return Maze;
}
}
EOF
评论框君很顽皮,需要科学上网才能看到哦!~
关注微信公众号(MarIxs)也能联系到我哦!