如何查找数组中的所有连接数字?

时间:2011-05-14 01:37:21

标签: java arrays continuous

嘿所有,又回来了。在地下城发电机上工作,我实际上对进展感到惊讶。然而,我时不时地仍然有一个分散的房间。我想知道是否有办法循环一个数组并查看所有'1'(地砖)是否已连接,如果没有,如何连接它们。

谢谢!

编辑:阵列随机填满房间和走廊;这是代码:

import java.util.Random;
public class Level
{
  Random random = new Random();
  int[][] A = new int[100][100];
  int minimum = 3;
  int maximum = 7;
  int xFeature = 0;
  int yFeature = 0;
private void feature()
  {
    int i = 0;
    while(i>=0)
    {
      xFeature = random.nextInt(100-1) + 1;
      yFeature = random.nextInt(100-1) + 1;
      if(A[xFeature][yFeature]==1)//||A[xFeature++][yFeature]==1||A[xFeature][yFeature--]==1||A[xFeature][yFeature++]==1)
        break;
      i++;
    }
  }


  private void room()
  {
    int safeFall = 0;
    int xCoPLUS = minimum + (int)(Math.random()*minimum);
    int yCoPLUS = minimum + (int)(Math.random()*minimum);
    if(yCoPLUS >= xCoPLUS)
    {
      for(int across = xFeature; across < xFeature+xCoPLUS+2; across++) 
      {
        for(int vert = yFeature; vert < yFeature+yCoPLUS+1; vert++)
        {
          if(A[vert][across] == 0)
            safeFall++;
          else
            break;
        }
      }
    }
    if(yCoPLUS < xCoPLUS)
    {
      for(int across = xFeature; across < xFeature+xCoPLUS+1; across++) 
      {
        for(int vert = yFeature; vert < yFeature+yCoPLUS+2; vert++)
        {
          if(A[vert][across] == 0)
            safeFall++;
          else
            break;
        }
      }
    }
    if((safeFall== (xCoPLUS+1) * (yCoPLUS+2)) || ((safeFall== (xCoPLUS+2) * (yCoPLUS+1))))
    {
      for(int across = xFeature; across < xFeature+xCoPLUS; across++) 
      {
        for(int vert = yFeature; vert < yFeature+yCoPLUS; vert++)
        {
          A[vert][across] = 1;
        }
      }
    }
  }
private void corridor()
  {

    int xCoONE = xFeature;
    int yCoONE = yFeature;
    int xCoTWO = random.nextInt(10)+10;
    int yCoTWO = random.nextInt(10)+10;
    while(xCoONE > xCoTWO)
    {
      A[xCoONE][yCoONE] = 1;
      xCoONE--;
    }
    while(xCoONE < xCoTWO)
    {
      A[xCoONE][yCoONE] = 1;
      xCoONE++;
    }
    while(yCoONE > yCoTWO)
    {
      A[xCoONE][yCoONE] = 1;
      yCoONE--;
    }
    while(yCoONE < yCoTWO)
    {
      A[xCoONE][yCoONE] = 1;
      yCoONE++;
    }
}
public Level()
  {
    firstroom();
    for(int i = 0; i < 500; i++)
    {
      int x = random.nextInt(50);
      feature();
      if(x > 1)
        room();
      else
        corridor();
    }
    troubleShoot();
  }

所以基本上当我创建这个类的对象时会发生的是100x100数组充满了由随机数确定的走廊和房间。 (好吧,他们中的几个)但是我的房间如何让我的房间不重叠故障保护(safeFall in room()),我时不时会遇到一个无法触及的房间。

Example

1 个答案:

答案 0 :(得分:0)

文章Maze Generation Algorithm讨论了产生迷宫的几种方法。它包含Java示例的链接。