2022. 11. 21. 10:44ใAlgorithm
๋ฐฑ์ค - ์ธ๊ตฌ์ด๋(Swift)
๋ฌธ์ ์ค๋ช
https://www.acmicpc.net/problem/16234
๋์ ํ์ด
์ด ๋ฌธ์ ๋ DFS, BFS๋ฌธ์ ๋ค. ๋ฒฝ์ด ํ๋ฌผ ์ ์๋ ํ ๊ณ์ ํ๋ฌธ๋ค ๋ฒฝ๋ค์ ํฉ์ ๊ฐ์๋ก ๋๋์ด ๋ฐฐ์ ํ๊ณ ๋ฅผ ๋ฐ๋ณตํ๋ฉด ๋๋ค.
๊ทธ๋ฆฌ๊ณ ์ด๋ฅผ "ํ๋ฌผ ์ ์๋ ๋ฒฝ์ด ์์๋"๊น์ง ์งํํ๊ธฐ ๋๋ฌธ์ ๋ง์ฝ tempMap์ด ๊ธฐ์กด์ map๊ณผ ๋์ผํ๋ค๋ฉด ํ์ถํด์ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ฉด ๋๋ค.
์ฒ์์๋ BFS์ธ์ง ๋ฐ๋กํ์ธํ์ง ๋ชปํ๊ณ ํค๋งค๋ค๊ฐ ๋ค๋ฅธ์ฌ๋์ ํ์ด๋ฅผ ๋ณด๊ณ ๊ฐ์ ์ ์๋ค. ๋ฒฝ์ด ํ๋ฌผ ์ ์๋ ๊ฒ๊ณผ ์ฐํฉ์ด๋ผ๋ ํค์๋๋ฅผ ๋ณด๊ณ ๋ฐ๋ก ๋ ์ฌ๋ฆด ์ ์์ด์ผํ๋๋ฐ ์์ง ๋ง์ด ๋ถ์กฑํ๋ค.
import Foundation
struct Point {
let r: Int
let c: Int
init(_ r: Int, _ c: Int) {
self.r = r
self.c = c
}
var nexts: [Point] {
return [
Point(r+1, c),
Point(r, c+1),
Point(r-1, c),
Point(r, c-1)
]
}
}
let nlr = readLine()!.components(separatedBy:" ").map{Int($0)!}
var map: [[Int]] = []
var tempMap: [[Int]] = []
var visited = [[Bool]]()
// N<=X<= R ๋ฒ์
let range = nlr[1]...nlr[2]
// ์ธ๊ตฌ์ด๋์ด ๋ฉฐ์น ๊ฐ ๋ฐ์ํ๋์ง
var cnt = 0
for _ in 0..<nlr[0] {
map.append(readLine()!.components(separatedBy:" ").map{Int($0)!})
}
while true {
tempMap = map
visited = [[Bool]](repeating: [Bool](repeating: false, count: nlr[0]), count: nlr[0])
for i in 0..<nlr[0] {
for j in 0..<nlr[0] {
guard !visited[i][j] else { continue }
BFS(Point(i, j))
}
}
if tempMap == map {
break
} else {
cnt += 1
map = tempMap
}
}
print(cnt)
func BFS(_ p: Point) {
var queue = [Point]()
// ๋ฒฝ์ด ํ๋ฌผ์ด์ง๋ ๊ณณ์ ํฉ
var sum = map[p.r][p.c]
var member = [Point]()
var partyCount = 1
queue.append(p)
visited[p.r][p.c] = true
while !queue.isEmpty {
let curr = queue.removeFirst()
member.append(curr)
for next in curr.nexts where 0..<nlr[0] ~= next.r && 0..<nlr[0] ~= next.c {
guard !visited[next.r][next.c] else { continue }
if range ~= abs(map[curr.r][curr.c] - map[next.r][next.c]) {
visited[next.r][next.c] = true
sum += map[next.r][next.c]
queue.append(Point(next.r, next.c))
partyCount += 1
}
}
}
for x in member {
tempMap[x.r][x.c] = sum / partyCount
}
}
ํผ๋๋ฐฑ
๋ฐฉ๋ฌธ์ฒ๋ฆฌ์ ๋ํด guard๋ฌธ์ ์ฐ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ธ ๊ฒ ๊ฐ๋ค. ๊ทธ๋ฆฌ๊ณ closedRange๋ฅผ ์ด์ฉํด์ ํจํด๋งค์นญ ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ์ ๊ณผ Point์ ๊ณ์ฐ์์ฑ nexts๋ฅผ ์ฌ์ฉํจ์ผ๋ก์จ ๋ค๊ฐ์ง ๋ฐฉ๋ฉด์ ๋ค๋ฃฌ ์ ์ ๋ฐฐ์ ๋ค.
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค - ์น์ฆ(Swift) (0) | 2022.11.22 |
---|---|
๋ฐฑ์ค - ํฑ๋๋ฐํด 2(Swift) (0) | 2022.11.21 |
๋ฐฑ์ค - ์นํจ๋ฐฐ๋ฌ(Swift) (0) | 2022.11.18 |
๋ฐฑ์ค - ํฑํํ (Swift) (0) | 2022.11.16 |
๋ฐฑ์ค - 0 ๋ง๋ค๊ธฐ(Swift) (0) | 2022.11.16 |