Easy to understand Swift solution


  • 0
    extension Collection where Indices.Iterator.Element == Index {
    	
    	subscript (safe index: Index) -> Generator.Element? {
    		return indices.contains(index) ? self[index] : nil
    	}
    	
    }
    
    func imageSmoother(_ M: [[Int]]) -> [[Int]] {
    	guard !M.isEmpty else { return [] }
    	
    	let traversalGridPoints = [
    		[0, -1],
    		[-1, 0],
    		[1, 0],
    		[0, 1],
    		[-1, -1],
    		[1, 1],
    		[1, -1],
    		[-1, 1]
    	]
    	
    	let traversalGridPointsCoordinates = traversalGridPoints.map { (x: $0[0], y: $0[1]) }
    	
    	let rows = M.count
    	let columns = M[0].count
    	
    	var result = Array(repeating: Array(repeating: 0, count: columns), count: rows)
    	
    	for y in M.indices {
    		for x in M[y].indices {
    			var sum = M[y][x]
    			var count = 1
    			
    			traversalGridPointsCoordinates.forEach({ coordinate in
    				if let value = M[safe: coordinate.y + y]?[safe: coordinate.x + x] {
    					sum += value
    					count += 1
    				}
    			})
    			
    			result[y][x] = sum / count
    		}
    	}
    	
    	return result
    }
    

Log in to reply
 

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