accepted ruby solution


  • 0
    B
    def update_matrix(matrix)
        m = matrix.size
        n = matrix[0].size
        queue = []
        (0...m).each do |i|
            (0...n).each do |j|
                if matrix[i][j] == 0
                    queue << [i,j]
                else
                    matrix[i][j] = 2**31 - 1
                end
            end
        end
        dirs = [[-1,0],[1,0],[0,-1],[0,1]]
        while !queue.empty?
            cell = queue.shift
            dirs.each do |d|
                r = cell[0] + d[0]
                c = cell[1] + d[1]
                next if r < 0 || r >= m || c < 0 || c >= n || matrix[r][c] <= matrix[cell[0]][cell[1]] + 1
                queue << [r,c]
                matrix[r][c] = matrix[cell[0]][cell[1]] + 1
            end
        end
        return matrix
    end
    

Log in to reply
 

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