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

Algorithm/Baekjoon

[๋ฐฑ์ค€](Swift) 2667๋ฒˆ - ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ (DFS์˜ ๊ฐ€์žฅ ๊ธฐ๋ณธ์ ์ธ ๋ฌธ์ œ)

๊ฐ์ž ๐Ÿฅ” 2022. 5. 27. 17:37
๋ฐ˜์‘ํ˜•

๐Ÿ’๐Ÿป ๋ฌธ์ œ๋งํฌ

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

 

2667๋ฒˆ: ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

<๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ์ •์‚ฌ๊ฐํ˜• ๋ชจ์–‘์˜ ์ง€๋„๊ฐ€ ์žˆ๋‹ค. 1์€ ์ง‘์ด ์žˆ๋Š” ๊ณณ์„, 0์€ ์ง‘์ด ์—†๋Š” ๊ณณ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ์ฒ ์ˆ˜๋Š” ์ด ์ง€๋„๋ฅผ ๊ฐ€์ง€๊ณ  ์—ฐ๊ฒฐ๋œ ์ง‘์˜ ๋ชจ์ž„์ธ ๋‹จ์ง€๋ฅผ ์ •์˜ํ•˜๊ณ , ๋‹จ์ง€์— ๋ฒˆํ˜ธ๋ฅผ ๋ถ™์ด๋ ค ํ•œ๋‹ค. ์—ฌ

www.acmicpc.net

 

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

์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ๋งŒ๋‚˜๋ฉด, ํ˜„์žฌ์œ„์น˜์—์„œ ์œ„, ์•„๋ž˜, ์˜ค๋ฅธ์ชฝ, ์™ผ์ชฝ์„ ์‚ดํŽด๋ณด๋ฉด์„œ ์—ฐ๊ฒฐ์ด ๋˜์–ด์žˆ๋‚˜? ๋ฅผ ํŒ๋‹จํ•ด์•ผํ•œ๋‹ค. 

์œ„ ๊ทธ๋ฆผ์„ ๋ณด๋ฉด, ํ˜„์žฌ ์œ„์น˜๋Š” (0,0)์ผ๋•Œ ๋ฐฉํ–ฅํ‚ค๋กœ ์›€์ง์ผ ์ˆ˜ ์žˆ๋‹ค. x์ขŒํ‘œ์ธ 0์—๋‹ค๊ฐ€ dx[2]์„ ๋”ํ•˜๊ณ , y์—๋‹ค๊ฐ€ dy[2]์„ ๋”ํ•ด์ฃผ๋ฉด, (1,0)์œผ๋กœ ํ•œ์นธ ์•„๋ž˜๋กœ ์ด๋™ํ•  ๊ฒƒ์ด๋‹ค. ์ด์ฒ˜๋Ÿผ ์ด๋ ‡๊ฒŒ "์—ฐ๊ฒฐ๋œ 1์„ ์ฐพ์•„ ๋ฌด์–ธ๊ฐ€๋ฅผ ์ฐพ๋Š”๋ฌธ์ œ"๋ผ๋ฉด, ์ด๋ ‡๊ฒŒ ๋ฐฉํ–ฅํ‚ค๋ฅผ ์ƒ๊ฐํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ๋œ๋‹ค.

์ง€๊ธˆ ๋ฌธ์ œ๋Š” 1์ด ์—ฐ๊ฒฐ๋˜์–ด์žˆ๋Š” ๋ถ€๋ถ„์„ '์ƒ‰์น 'ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„๋Œ€๋กœ, 1์ด ์—ฐ๊ฒฐ๋˜์–ด์žˆ์œผ๋ฉด ํ•˜๋‚˜์˜ ๋‹จ์ง€๊ฐ€ ๋˜๋Š” ๊ฒƒ์ด๋‹ค.
๋‚˜๋Š” dfs๋ฅผ ์ด์šฉํ•ด์„œ 1์ธ ๊ณณ์„ ์ „๋ถ€ ๋ฐฉ๋ฌธํ•˜๊ณ , ๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด 0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๋Š” ๋ฐฉ์‹์„ ์„ ํƒํ–ˆ๋‹ค.

 

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

https://github.com/deslog/Algorithm/blob/main/Algorithm/Boj/2667_%EB%8B%A8%EC%A7%80%20%EB%B2%88%ED%98%B8%20%EB%B6%99%EC%9D%B4%EA%B8%B0/main.swift

 

GitHub - deslog/Algorithm

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

github.com

let n = Int(String(readLine()!))!
var graph = [[Int]]()
var cntList = [Int]()
var cnt = 0
let dx = [-1, 1, 0, 0] //์œ„ ์•„ ์™ผ ์˜ค
let dy = [0, 0, -1, 1]

for _ in 0..<n {
    graph.append(Array(readLine()!.map{ Int(String($0))! }))
}

func dfs(_ i: Int, _ j: Int) -> Int {
    var deque = [(Int, Int)]()
    deque.append((i, j))
    graph[i][j] = 0 // ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ
    cnt = 1
    
    while !deque.isEmpty {
        let tem = deque.removeFirst()
        let x = tem.0
        let y = tem.1
        
        for k in 0..<4 {
            let nx = x + dx[k]
            let ny = y + dy[k]
            
            if nx < 0 || ny < 0 || nx >= n || ny >= n {
                continue
            }
            
            if graph[nx][ny] == 1 {
                graph[nx][ny] = 0
                deque.append((nx, ny))
                cnt += 1
            }
        }
    }
    return cnt
}

for i in 0..<n {
    for j in 0..<n {
        if graph[i][j] == 1 {
            cntList.append(dfs(i,j))
        }
    }
}

print(cntList.count)
cntList.sort()
for i in cntList {
    print(i)
}
๋ฐ˜์‘ํ˜•