Swift solution with full comments


  • 0
    S

    Problem doesn't have a Swift option, but here's an usable Swift solution

    class Solution {
        func multiply(_ A: [[Int]], _ B: [[Int]]) -> [[Int]] {
            // B.rows.count must equal A.cols.count
            
            // preallocate a 2D array of size [A rows][B cols]
            var AB: [[Int]] = [[Int]](repeating: [Int](repeating: 0, count:B[0].count), count: A.count)
            
            // iterate through A in row / col order
            for arow in 0..<A.count {
                for acol in 0..<A[0].count {
                    // if we have a zero, AB preset will not change
                    if A[arow][acol] != 0 {
                        // B.rows == A.cols, so just iterate B.cols
                        for bcol in 0..<B[0].count {
                            // invert B' using acol for B.row
                            AB[arow][bcol] += A[arow][acol] * B[acol][bcol]
                        }
                    }
                }
            }
            
            return AB
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.