Swift Data Structure And Algorithm/Graph Algorithm
๋จ์ง ๋ฒํธ ๋ถ์ด๊ธฐ_DFS
youngjaeLee1026
2022. 4. 15. 11:44
1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ๊ทธ๋ฆผ 1 ์ฒ๋ผ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ 2์ฐจ์ ๋ฐฐ์ด์ ๊ทธ๋ํ๋ผ๊ณ ๊ฐ์ ํ๊ณ , ํ์ฌ ์์๊ฐ 1์ด๋ผ๋ฉด ์, ํ, ์ข, ์ฐ ๋ฐฉํฅ์ผ๋ก ๊ทธ๋ํ ํ์(DFS or BFS)์ ์งํํ๊ณ , ๋์ด์ ์, ํ, ์ข, ์ฐ์ ์ธ์ ํ ์์ 1์ด ์๋ค๋ฉด ํ์์ ๋ฉ์ถ๊ณ ๊ทธ ๋์ count ๊ฐ์ ๋ณ๋์ ๋ฐฐ์ด ํน์ ๋ฆฌ์คํธ์ ์ ์ฅ
- ์ด ๋ฌธ์ ์ ๊ฒฝ์ฐ, 2์ฐจ์ ๋ฐฐ์ด์ ์ ๋ ฅ์ ์ฃผ์ํด์ผ ํ๋๋ฐ, ํ ์ค ๋จ์๋ก ์ ๋ ฅ์ ๋ฐ๊ณ ์๊ธฐ ๋๋ฌธ์, ๋ฌธ์์ด์ ๊ฐ๊ฐ์ ์์๋ฅผ ์ ์๋ก ๋ณํํ์ฌ ๋ฐฐ์ด์ ๊ตฌ์ฑํด์ผ ํจ
- ๋ง์ง๋ง์ผ๋ก, count ๊ฐ์ ๋ด์ ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌํ๊ณ , ๋ฆฌ์คํธ์ ํฌ๊ธฐ์ ์์๋ฅผ ์ฐจ๋ก๋ก ์ถ๋ ฅํจ์ผ๋ก์จ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - ๋จ์ง ๋ฒํธ ๋ถ์ด๊ธฐ
//MARK: - Framework
import Foundation
//MARK: - Variable
var graph: [[Int]] = []
var visited: [[Bool]] = []
var count: Int = 0
//MARK: - Function
func dfs(_ x: Int, _ y: Int) -> Void {
let dx: [Int] = [-1, 1, 0, 0]
let dy: [Int] = [0, 0, -1, 1]
visited[x][y] = true
count += 1
for i in 0..<dx.count {
let nx: Int = x + dx[i]
let ny: Int = y + dy[i]
if graph[nx][ny] == 1 && !visited[nx][ny] {
dfs(nx, ny)
}
}
}
func solution() -> Void {
//MARK: - Input
guard let N: Int = Int(readLine() ?? "0") else { return }
var homeCounts: [Int] = []
graph = Array(repeating: Array(repeating: 0, count: N + 10), count: N + 10)
visited = Array(repeating: Array(repeating: false, count: N + 10), count: N + 10)
for i in 1...N {
guard let str: String = readLine() else { return }
for j in 0..<str.count {
graph[i][j + 1] = Int("\(str[str.index(str.startIndex, offsetBy: j)])") ?? 0
}
}
//MARK: - Process
for i in 1...N {
for j in 1...N {
if graph[i][j] == 1 && !visited[i][j] {
dfs(i, j)
homeCounts.append(count)
count = 0
}
}
}
homeCounts.sort { $0 < $1 }
//MARK: - Output
print(homeCounts.count)
for count in homeCounts {
print(count)
}
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.