DFS函数用于在二维数组中查找返回错误数字的孤岛

时间:2019-02-15 02:07:15

标签: swift

我正在尝试编写一个函数,该函数查看2D数组并返回“ islands”,即基本上不为0的任何数字的簇。简化后,我在下面声明了应该返回5的图-因为在5个地方,1被分组/单独并且被零包围。谁能看到这段代码有什么问题吗?

    func numIslands(grid: [Array<Int>]) -> Int{
        if(grid == nil || grid.count == 0 || grid[0].count == 0){
            return 0
        }

        let m = grid.count
        let n = grid[0].count

        var count = 0
        for i in 0...m-1{
            for j in 0...n-1{
                if grid[i][j] >= 1 {
                    count += 1
                    merge(grid: grid, i: i, j: j);
                }
            }
        }
        return count;
    }

    func merge(grid: [Array<Int>], i: Int, j: Int){
        var grid = grid
        let m = grid.count
        let n = grid[0].count

        if(i < 0 || i >= m || j<0 || j >= n || grid[i][j] != 1){
            return
        }

        grid[i][j] = 0

        merge(grid: grid, i: i-1, j:j)
        merge(grid: grid, i: i+1, j:j)
        merge(grid: grid, i: i, j: j-1)
        merge(grid: grid, i: i, j: j+1)
    }


    var graph = [[1, 1, 0, 0, 0],
                 [0, 1, 0, 0, 1],
                 [1, 0, 0, 1, 1],
                 [0, 0, 0, 0, 0],
                 [1, 0, 1, 0, 1]]


    print(numIslands(grid: graph))
    //returns 10, should be 5

1 个答案:

答案 0 :(得分:1)

主要错误在这里:

func merge(grid: [Array<Int>], i: Int, j: Int) {
    var grid = grid // Make a mutable copy

    // ... modify `grid` ...
}

数组是Swift中的值类型merge()函数修改局部可变变量grid,但不修改传递的参数。因此,在主循环中

var count = 0
for i in 0...m-1{
    for j in 0...n-1{
        if grid[i][j] >= 1 {
            count += 1
            merge(grid: grid, i: i, j: j);
        }
    }
}

网格从未修改,循环仅计算>= 1条目的数量。

您需要的是一个“输入参数”

func merge(grid: inout [Array<Int>], i: Int, j: Int){
    let m = grid.count
    let n = grid[0].count

    if(i < 0 || i >= m || j<0 || j >= n || grid[i][j] != 1){
        return
    }

    grid[i][j] = 0

    merge(grid: &grid, i: i-1, j:j)
    merge(grid: &grid, i: i+1, j:j)
    merge(grid: &grid, i: i, j: j-1)
    merge(grid: &grid, i: i, j: j+1)
}

,只有main函数进行复制,并使用&作为inout参数将其传递给函数:

var grid = grid
// ...
merge(grid: &grid, i: i, j: j);

进行此更改后,结果将是6(而不是预期的5),因为merge()不会合并对角线邻居。但这现在应该很容易解决。