1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ๊ทธ๋ฆผ 1 ์ฒ๋ผ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ 2์ฐจ์ ๋ฐฐ์ด์ ๊ทธ๋ํ๋ผ๊ณ ๊ฐ์ ํ๊ณ , ํ์ฌ ์์๊ฐ 1์ด๋ผ๋ฉด ์, ํ, ์ข, ์ฐ ๋ฐฉํฅ์ผ๋ก ๊ทธ๋ํ ํ์(DFS or BFS)์ ์งํํ๊ณ , ๋์ด์ ์, ํ, ์ข, ์ฐ์ ์ธ์ ํ ์์ 1์ด ์๋ค๋ฉด ํ์์ ๋ฉ์ถ๊ณ ๊ทธ ๋์ count ๊ฐ์ ๋ณ๋์ ๋ฐฐ์ด ํน์ ๋ฆฌ์คํธ์ ์ ์ฅ
- ์ด ๋ฌธ์ ์ ๊ฒฝ์ฐ, 2์ฐจ์ ๋ฐฐ์ด์ ์ ๋ ฅ์ ์ฃผ์ํด์ผ ํ๋๋ฐ, ํ ์ค ๋จ์๋ก ์ ๋ ฅ์ ๋ฐ๊ณ ์๊ธฐ ๋๋ฌธ์, ๋ฌธ์์ด์ ๊ฐ๊ฐ์ ์์๋ฅผ ์ ์๋ก ๋ณํํ์ฌ ๋ฐฐ์ด์ ๊ตฌ์ฑํด์ผ ํจ
- ๋ง์ง๋ง์ผ๋ก, count ๊ฐ์ ๋ด์ ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌํ๊ณ , ๋ฆฌ์คํธ์ ํฌ๊ธฐ์ ์์๋ฅผ ์ฐจ๋ก๋ก ์ถ๋ ฅํจ์ผ๋ก์จ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - ๋จ์ง ๋ฒํธ ๋ถ์ด๊ธฐ - BFS
//MARK: - Framework
import Foundation
//MARK: - Type
struct Node {
//MARK: - Property
var x, y: Int
//MARK: - Initializer
init(_ x: Int, _ y: Int) {
self.x = x
self.y = y
}
}
//MARK: - Variable
var graph: [[Int]] = []
var visited: [[Bool]] = []
var dx: [Int] = [-1, 1, 0, 0]
var dy: [Int] = [0, 0, -1, 1]
//MARK: - Function
func bfs(_ x: Int, _ y: Int) -> Int {
var result: Int = 1
var queue: [Node] = []
queue.append(Node(x, y))
visited[x][y] = true
while !queue.isEmpty {
let currentNode: Node = queue.removeFirst()
for i in 0..<4 {
let nx: Int = currentNode.x + dx[i]
let ny: Int = currentNode.y + dy[i]
if !visited[nx][ny] && graph[nx][ny] == 1 {
visited[nx][ny] = true
queue.append(Node(nx, ny))
result += 1
}
}
}
return result
}
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 data: String = readLine() else { return }
for j in 1...N {
graph[i][j] = Int("\(data[data.index(data.startIndex, offsetBy: j - 1)])")!
}
}
//MARK: - Process
for i in 1...N {
for j in 1...N {
if graph[i][j] == 1 && !visited[i][j] {
homeCounts.append(bfs(i, j))
}
}
}
homeCounts.sort { $0 < $1 }
//MARK: - Output
print(homeCounts.count)
for count in homeCounts {
print(count)
}
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.
'Swift Data Structure And Algorithm > Graph Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ ์ผ๋ณ (0) | 2022.04.15 |
---|---|
์ด์ํ ๊ณ์ฐ๊ธฐ (0) | 2022.04.15 |
๋ฏธ๋ก ์ฐพ๊ธฐ (0) | 2022.04.15 |
์ ๋ฐ์ด๋ฌ์ค_BFS (0) | 2022.04.15 |
์ด๋ถ ๊ทธ๋ํ ํ๋ณ_BFS (0) | 2022.04.15 |