본문 바로가기
알고리즘

[Swift] LeetCode - 200. Number of Islands

by 고고 2022. 2. 16.

문제: https://leetcode.com/problems/number-of-islands/

 

Number of Islands - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

DFS로 풀었습니다.

import Foundation

class Solution {
    func numIslands(_ grid: [[Character]]) -> Int {
        var result = 0
        var visited = Array(repeating: Array(repeating: false, count: grid[0].count), count: grid.count)
        
        let dx = [-1, 1, 0, 0]
        let dy = [0, 0, -1, 1]
        
        func dfs(_ x: Int, _ y: Int) {
            visited[x][y] = true
            
            for i in 0...3 {
                let nx = x + dx[i]
                let ny = y + dy[i]
                
                if nx < 0 || ny < 0 || nx >= grid.count || ny >= grid[0].count {
                    continue
                }
                if visited[nx][ny] { continue }
                
                if grid[nx][ny] == "1" {
                    dfs(nx, ny)
                }
            }
        }
        
        for i in 0..<grid.count {
            for j in 0..<grid[i].count {
                if grid[i][j] == "1" && !visited[i][j] {
                    result += 1
                    dfs(i, j)
                }
            }
        }
        
        
        return result
    }
}

댓글