Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 4963๋ฒˆ - ์„ฌ์˜ ๊ฐœ์ˆ˜ (DFS ํ’€์ด)

๊ฐ์ž ๐Ÿฅ” 2022. 6. 1. 18:28
๋ฐ˜์‘ํ˜•

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

https://www.acmicpc.net/problem/4963

 

4963๋ฒˆ: ์„ฌ์˜ ๊ฐœ์ˆ˜

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ง€๋„์˜ ๋„ˆ๋น„ w์™€ ๋†’์ด h๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. w์™€ h๋Š” 50๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์–‘์˜ ์ •์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ h๊ฐœ ์ค„์—๋Š” ์ง€๋„

www.acmicpc.net

 

๐Ÿ’ป ๋ฌธ์ œํ’€์ด

  • ๊ฐ€์žฅ ๊ธฐ๋ณธ์ ์ธ DFS๋ฌธ์ œ (BFS๋„ ๊ฐ€๋Šฅ)
  • ๊ทธ๋ž˜ํ”„๋กœ ์ž…๋ ฅ ๋ฐ›์€ ํ›„, 1์ธ ๊ณณ์„ ์ „๋ถ€ ํƒ์ƒ‰ → ํƒ์ƒ‰ํ•˜๋ฉด์„œ ํ•ด๋‹น ์œ„์น˜ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
  • ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ ๋œ ๊ณณ๋“ค์„ ๋Œ์•„๋‹ค๋‹ˆ๋‹ค๊ฐ€ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌํ•  ๊ณณ์ด ์—†์œผ๋ฉด count += 1
  • ์ตœ์ข…์ ์œผ๋กœ count ์ถœ๋ ฅ

 

๐Ÿ’ป ์†Œ์Šค์ฝ”๋“œ

https://github.com/deslog/Algorithm/blob/main/Algorithm/Boj/4963_%EC%84%AC%EC%9D%98%EA%B0%9C%EC%88%98/main.swift

 

GitHub - deslog/Algorithm

Contribute to deslog/Algorithm development by creating an account on GitHub.

github.com

let dx = [-1, 1, 0, 0, -1, -1, 1, 1]
let dy = [0, 0, -1, 1, -1, 1, -1, 1] //์œ„ ์•„ ์™ผ ์˜ค ์™ผ์ชฝ์œ„ ์˜ค๋ฅธ์ชฝ์œ„ ์™ผ์ชฝ์•„๋ž˜ ์˜ค๋ฅธ์ชฝ์•„๋ž˜
while true {
    var count = 0
    let wh = readLine()!.split(separator: " ").map{ Int(String($0))! }
    
    if wh == [0, 0] {
        break
    }

    var islandMap: [[Int]] = []
    var visited = Array(repeating: Array(repeating: false, count: wh[0]), count: wh[1])

    for _ in 0..<wh[1] {
        islandMap.append(readLine()!.split(separator: " ").map { Int(String($0))! })
    }
    func dfs(_ x: Int, _ y: Int) {
        for i in 0..<dx.count {
            let nx = x + dx[i]
            let ny = y + dy[i]

            if nx < 0 || nx > wh[0]-1 || ny < 0 ||  ny > wh[1]-1 {
                continue
            } else {
                if !visited[nx][ny] && islandMap[nx][ny] == 1 {
                    visited[nx][ny] = true
                    dfs(ny, nx)
                }
            }
        }
    }

    // main
    for i in 0..<wh[1] {
        for j in 0..<wh[0] {
            if islandMap[i][j] == 1 && !visited[i][j] {
                visited[i][j] = true
                dfs(i, j)
                count += 1
            }
        }
    }
    print(count)
}
๋ฐ˜์‘ํ˜•