剑指 Offer II 107. 矩阵中的距离

首先想到的dfs 1600ms弱爆了。唉


func updateMatrix(_ mat: [[Int]]) -> [[Int]] {
        
        let row = mat.count
        let col = mat.first!.count
        let temp = Array.init(repeating: 0, count: col)
        var res = Array.init(repeating: temp, count: row)
        var tempMat = mat

        for i in 0..= row || j >= col {
            return
        }
        if mat[i][j] == 0 {
            minCount = min(minCount,count)
            return
        }
        if count > minCount {
            return
        }
        if mat[i][j] == 1 {
            mat[i][j] = 2
            dfs(i, j + 1 , row, col,&minCount, count + 1,&res,&mat)
            dfs(i, j - 1 , row, col,&minCount, count + 1,&res,&mat)
            dfs(i + 1, j , row, col,&minCount, count + 1,&res,&mat)
            dfs(i - 1, j , row, col,&minCount, count + 1,&res,&mat)
            mat[i][j] = 1
        }

    }

你可能感兴趣的:(剑指 Offer II 107. 矩阵中的距离)