【问题标题】:Objective C, maze generation and 2D arraysObjective C,迷宫生成和二维数组
【发布时间】:2012-11-25 05:44:00
【问题描述】:

我需要生成一个具有给定宽度和高度的随机迷宫。我可以在 Perl 中使用深度优先搜索算法执行此操作,其中我使用 2D 数组,如下所示:

    for my $i (0 .. $h - 1) {
        for my $j (0 .. $w - 1) {
            push @{ $cell[$i] }, '1';
        }
        push @{ $cell[$i] }, '0';
    }
    for my $i (0 .. $w) {
        $cell[$h][$i] = '';
    }

在 Objective C 中,没有二维数组。我现在有点迷路了。 Objective C 中二维数组的等价物是什么,所以我几乎可以使用与 Perl 中相同的数据结构? 谢谢。

【问题讨论】:

  • 在数组中使用数组:stackoverflow.com/questions/4362740/…
  • 再复习一下数据结构——这应该很明显。
  • Objective-C 只是 C 的超集,因此您可以使用 C 中的普通旧二维数组,如下所示:int twoDimArray[][]

标签: objective-c multidimensional-array maze


【解决方案1】:

一种方法是使用Objective-C风格的数组:

NSMutableArray *cell = [NSMutableArray arrayWithCapacity:h];
for (int i=0; i<h; ++i) {
    NSMutableArray *row = [NSMutableArray arrayWithCapacity:w];
    for (int j=0; j<w; ++j) {
        // use a random number
        [row addObject:[NSNumber numberWithInt:rand()]];
    }
    // add one row
    [cell addObject:row];
}

另一种方法就是使用C风格的数组:

int **cell = malloc(h*sizeof(int *));
for (int i=0; i<h; ++i) {
    cell[i] = malloc(w*sizeof(int));
    for (int j=0; j<w; ++j) {
        cell[i][j] = rand();
    }
}

// after you used it remeber to free it
for (int i=0; i<h; ++i) {
    free(cell[i]);
}
free(cell);
cell = NULL;

【讨论】:

    【解决方案2】:

    使用这个github库生成迷宫。
    https://github.com/DoubleEqual/MazeGenerator-tool

    24x24 迷宫的结果如下所示:

    【讨论】:

    • 迷宫生成器工具代码有版权还是可以免费使用?
    【解决方案3】:

    二维或 N 维数组只不过是一种存储数据的方式。如果你想要一个二维数组,它相当简单,但在 obj-c 中有点棘手,你必须创建第二级数组,然后将其插入第一级。

    请看下面的代码:

    NSMutableArray *twoDArray = [NSMutableArray new]; //this is first level
    
    //below are second level arrays inserted in index 0 to 2.
    [twoDArray insertObject:[NSMutableArray arrayWithObjects:@"00",@"01",@"02",nil] atIndex:0];
    [twoDArray insertObject:[NSMutableArray arrayWithObjects:@"10",@"11",@"12",nil] atIndex:1];
    [twoDArray insertObject:[NSMutableArray arrayWithObjects:@"20",@"21",@"22",nil] atIndex:2];
    

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多