LeetCode 200. Number of Islands [Swift 题解]

题目

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:  
11110  
11010  
11000  
00000

Output: 1  

Example 2:

Input:  
11000  
11000  
00100  
00011

Output: 3  

原题链接

思路

比较典型的DFS或者BFS traverse的题型,个人比较倾向于DFS,比较直观一些。

class Solution {  
    func numIslands(_ grid: [[Character]]) -> Int {
        guard !grid.isEmpty else {
            return 0
        }

        let zero = Character("0")

        var visited = Set<String>()
        var count = 0

        func traverse(row: Int, col: Int, visited: inout Set<String>) {
            if row < 0 || row >= grid.count {
                return
            }

            if col < 0 || col >= grid.first!.count {
                return
            }

            let key = "\(row)-\(col)"
            if visited.contains(key) {
                return
            }

            visited.insert(key)
            if grid[row][col] == zero {
                return
            }

            traverse(row: row - 1, col: col, visited: &visited)
            traverse(row: row, col: col - 1, visited: &visited)
            traverse(row: row + 1, col: col, visited: &visited)
            traverse(row: row, col: col + 1, visited: &visited)
        }

        for (rowIndex, row) in grid.enumerated() {
            for (colIndex, col) in row.enumerated() {
                let key = "\(rowIndex)-\(colIndex)"
                if visited.contains(key) {
                    continue
                }

                if col == zero {
                    visited.insert(key)
                    continue
                }

                count += 1
                traverse(row: rowIndex, col: colIndex, visited: &visited)
            }
        }

        return count
    }
}

chenbo

编程爱好者

Singapore