Very simple Go solution


  • 0
    I

    O(N) space and computational complexity. Unlike the other solutions (as of writing), it uses a simple for loop to sum the surrounding cells. No reason to initialize an array!

    func imageSmoother(in [][]int) [][]int {
        m, n := len(in), len(in[0])
        out := make([][]int, m)
        for r := range in {
            out[r] = make([]int, n)
        }
        
        for r := range in {
            for c := range in[r] {
                var count int
                for offsetR := -1; offsetR <= 1; offsetR++ {
                    for offsetC := -1; offsetC <= 1; offsetC++ {
                        x, y := r+offsetR, c+offsetC
                        if x >= 0 && x < m && y >= 0 && y < n {
                            out[r][c] += in[x][y]
                            count++
                        }
                    }
                }
                out[r][c] /= count // count will never be zero
            }
        }
        return out
    }
    

Log in to reply
 

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