随笔 - 79  文章 - 58  trackbacks - 0
<2016年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(9)

随笔分类

随笔档案

文章档案

相册

搜索

  •  

积分与排名

  • 积分 - 291999
  • 排名 - 87

最新评论

阅读排行榜

评论排行榜

import java.util.Random;

public class maze {
 private char map[][];
 private Random rand = new Random();
 //纵横
 private final int x = 11, y = 15;

 public maze() {
  map = new char[50][50];
 }

 public void printMaze() {
  int z1, z2;
  for (z2 = 1; z2 <= x * 2 + 1; z2++) {
   for (z1 = 1; z1 <= y * 2 + 1; z1++) {
    if (map[z2][z1] == 0) {
     System.out.print(" ");
    } else {
     System.out.print("▉");
    }
   }
   System.out.println();
  }
  System.out.println();
 }

 public void makeMaze() {
  rand.setSeed(System.currentTimeMillis());
  int z1, z2;
  for (int i = 0; i <= x * 2 + 2; ++i)
   for (int j = 0; j <= y * 2 + 2; ++j)
    map[i][j] = 1;
  for (z1 = 0, z2 = 2 * y + 2; z1 <= 2 * x + 2; ++z1) {
   map[z1][0] = 0;
   map[z1][z2] = 0;
  }
  for (z1 = 0, z2 = 2 * x + 2; z1 <= 2 * y + 2; ++z1) {
   map[0][z1] = 0;
   map[z2][z1] = 0;
  }
  map[2][1] = 0;
  map[2 * x][2 * y + 1] = 0;

  searchPath(rand() % x + 1, rand() % y + 1);
 }

 private int searchPath(int x, int y) {
  int dir[][] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
  int zx = x * 2;
  int zy = y * 2;
  int next, turn, i;
  map[zx][zy] = 0;
  turn = 3;
  if (rand() % 2 == 1)
   turn = 1;
  for (i = 0, next = rand() % 4; i < 4; ++i, next = (next + turn) % 4) {
   if (map[zx + 2 * dir[next][0]][zy + 2 * dir[next][1]] == 1) {
    map[zx + dir[next][0]][zy + dir[next][1]] = 0;
    searchPath(x + dir[next][0], y + dir[next][1]);
   }
  }
  return 0;
 }

 private int rand() {
  return Math.abs(rand.nextInt());
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  maze m = new maze();
  m.makeMaze();
  m.printMaze();
 }

}

posted on 2012-02-14 21:38 merlinfang 阅读(882) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理