Swift solution - BFS


  • 0
    class Solution {
        private let directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
        
        func updateMatrix(_ matrix: [[Int]]) -> [[Int]] {
            let m = matrix.count
            let n = matrix[0].count
            var result = matrix
            var queue = [[Int]]()
            
            for i in 0..<m {
                for j in 0..<n {
                    if result[i][j] == 0 {
                        queue.append([i, j])
                    } else {
                        result[i][j] = Int.max
                    }
                }
            }
            
            while !queue.isEmpty {
                let cell = queue.removeFirst()
                for direction in self.directions {
                    let x = cell[0] + direction[0]
                    let y = cell[1] + direction[1]
                    if x < 0 || x >= m || y < 0 || y >= n || result[x][y] <= result[cell[0]][cell[1]] + 1 {
                        continue
                    }
                    queue.append([x, y])
                    result[x][y] = result[cell[0]][cell[1]] + 1
                }
            }
            
            return result
        }
    }
    

Log in to reply
 

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