Swift Solution


  • 0
    S
    func islandPerimeter(_ grid: [[Int]]) -> Int {
        
        let rowCount = grid.count
        let cellCount = grid.first?.count ?? 0
        
        guard rowCount > 0 && cellCount > 0 else { return 0 }
        
        var cellIndex = 0
        var rowIndex = 0
        
        var perimeter = 0
        
        while rowIndex < rowCount && cellIndex < cellCount {
            let cellValue = grid[rowIndex][cellIndex]
            
            if cellValue == 1 {
                
                var borderCount = 0
    
                // Check above row
                let rowAboveIndex = rowIndex - 1
                if rowAboveIndex >= 0 {
                    let aboveCellValue = grid[rowAboveIndex][cellIndex]
                    borderCount += aboveCellValue == 0 ? 1 : 0
                } else {
                    borderCount += 1
                }
                
                // Check left row
                let cellLeftIndex = cellIndex - 1
                if cellLeftIndex >= 0 {
                    let leftCellValue = grid[rowIndex][cellLeftIndex]
                    borderCount += leftCellValue == 0 ? 1 : 0
                } else {
                    borderCount += 1
                }
                
                // Check right row
                let cellRightIndex = cellIndex + 1
                if cellRightIndex < cellCount {
                    let rightCellValue = grid[rowIndex][cellRightIndex]
                    borderCount += rightCellValue == 0 ? 1 : 0
                } else {
                    borderCount += 1
                }
                
                // Check bottom row
                let rowBelowIndex = rowIndex + 1
                if rowBelowIndex < rowCount {
                    let belowCellValue = grid[rowBelowIndex][cellIndex]
                    borderCount += belowCellValue == 0 ? 1 : 0
                } else {
                    borderCount += 1
                }
                print(rowIndex)
                print(borderCount)
                perimeter += borderCount
            }
            
            if cellIndex == cellCount - 1 {
                rowIndex += 1
                cellIndex = 0
            } else {
                cellIndex += 1
            }
    
            
        }
        
        return perimeter
    }
    

Log in to reply
 

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