Easy to understand Swift solution


  • 0
    extension Collection {
    	
    	subscript (safe index: Index) -> Element? {
    		return indices.contains(index) ? self[index] : nil
    	}
    	
    }
    
    func islandPerimeter(_ grid: [[Int]]) -> Int {
    	let traversalGridPoints = [
    		[0, -1],
    		[-1, 0],
    		[1, 0],
    		[0, 1]
    	]
    	
    	let traversalGridPointsCoordinates = traversalGridPoints.map { (x: $0[0], y: $0[1]) }
    	var perimeter = 0
    	
    	for y in grid.indices {
    		for x in grid[y].indices {
    			guard grid[y][x] == 1 else {
    				continue
    			}
    			
    			traversalGridPointsCoordinates.forEach({ coordinate in
    				if grid[safe: coordinate.y + y]?[safe: coordinate.x + x] != 1 {
    					perimeter += 1
    				}
    			})
    		}
    	}
    	
    	return perimeter
    }
    

    Using safe method from extension to avoid out of bounds elements. Loop will first try to find a land field, and count a perimeter by counting water fields (which means that current land field doesn't have any neighbours on that side).


Log in to reply
 

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