BOJ: #14502 - ์ฐ๊ตฌ์
์ค๊ฐ๋ถํฐ ์๊ฐ ์ฌ๋ค๊ฐ ๋ง์์ง๋ง, ๊ฑฐ์ ๋ค์ฏ์๊ฐ ๊ฐ๊น์ด ๋ถ์ก์๋ค. ใ ใ
ํ๊ธฐ ์์ํ ์ง ๋ ์๊ฐ์ด ์ง๋ฌ์ ๋ ์ฏ์์ ์ฌ๋์ ๋ฌผ์ด๋ดค๊ณ ๋ ๊ฐ์ง ์กฐ์ธ์ ๋ค์๋ค.
board
์ ์ฒด๋ฅผ ๋๋ฉด์ 2๊ฐ ๋์ฌ ๋๋ง๋ค BFS๋ฅผ ๋๋ฆฌ๋ ๊ฒ ๋ณด๋ค 2๊ฐ ์๋ ์์น๋ฅผ ๋ฏธ๋ฆฌ ์ ์ฅํด๋๊ณ BFS๋ฅผ ๋๋ฆฌ๋ ๊ฒ ๋ ๋ซ๋ค.!visited.contains([nx, ny])
์ ์๊ฐ ๋ณต์ก๋๊ฐ O(N)์ด๋ฏ๋ก ๋ ๋น ๋ฅด๊ฒ ์ฐพ์ ์ ์๋ ๋ฐฉ๋ฒ์ผ๋ก ๋ฐ๊ฟ๋ผ.
์กฐ์ธ ํด์ฃผ์ ๋๋ก 1, 2๋ฅผ ์์ ํ๋ค.
- 2๊ฐ ์๋ ์์น๋ฅผ
virusLocation
์ ์ ์ฅํ๋ค. visited
๋ฅผSet
์ผ๋ก ๋ณ๊ฒฝํ๋ค.Set.contains()
์ ์๊ฐ ๋ณต์ก๋๋ O(1)
๋ก์ปฌ์์๋ ๋์ ๋๊ฒ ์ฑ๋ฅ ํฅ์์ด ์์์ง๋ง ์ฌ์ ํ ๋ฐฑ์ค์์๋ ์๊ฐ ์ด๊ณผ์๋ค. ๊ทธ๋์ ์ค์ํํธ๋ก ํต๊ณผํ์ ๋ถ์ ํ์ด๋ฅผ ์ฐธ๊ณ ํ๋ค.
๊ทธ๋ฆฌ๊ณ ๋ด ์ฝ๋์์ ๋ค์๊ณผ ๊ฐ์ ์ ์ ๋ณ๊ฒฝํ๋ค.
- ํจ์๋ฅผ ๋ถ๋ฆฌํ๋ค.
- 2์ฐจ์ ๋ฐฐ์ด๋ก ์ ์ฅํ๋
virusLocation
์[(Int, Int)]
ํํ๋ก ์ ์ฅํ๋ค. - ๋ฐ์ด๋ฌ์ค๊ฐ ํผ์ ธ๋๊ฐ๋
bfs()
์์visited
๋ฅผ ์์ ๋ ๋์copyBoard[nx][ny]
๊ฐ 0์ธ์ง ํ์ธํ๋ ์กฐ๊ฑด์ผ๋ก ๋ณ๊ฒฝํ๋ค.
์์ง๋ ๋ถ์กฑํ ๊ฒ ๋ง๋ค๋ ๊ฑธ ๋๊ผ๋ค.
๋ฌธ์
https://www.acmicpc.net/problem/14502
๋ด๊ฐ ์์ฑํ ์ฝ๋
Swift
let size = readLine()!.split(separator: " ").map { Int(String($0))! }
let n = size[0]
let m = size[1]
var board = [[Int]]()
for _ in 0..<n {
let line = readLine()!.split(separator: " ").map { Int(String($0))! }
board.append(line)
}
var copyBoard = board
var results = [[[Int]]]()
var picked = [[Int]]()
var visited = Array(repeating: Array(repeating: false, count: m), count: n)
func makeWall(toPick: Int) {
if toPick == 0 {
results.append(picked) // ์กฐํฉ ์ ์ฅ
return
}
for i in 0..<n {
for j in 0..<m {
if board[i][j] != 0 {
continue
}
if visited[i][j] {
continue
}
visited[i][j] = true
picked.append([i, j])
makeWall(toPick: toPick - 1)
picked.removeLast()
visited[i][j] = false
}
}
}
var virusLocation = [(Int, Int)]()
for i in 0..<n {
for j in 0..<m {
if board[i][j] == 2 {
virusLocation.append((i, j))
}
}
}
func safeArea() -> Int {
var count = 0
for i in 0..<n {
for j in 0..<m {
if copyBoard[i][j] == 0 {
count += 1
}
}
}
return count
}
let dx = [1, 0, -1, 0]
let dy = [0, 1, 0, -1]
func bfs(_ i: Int, _ j: Int) {
// ๋ฐ์ด๋ฌ์ค๊ฐ ํผ์ ธ๋๊ฐ๋ ์์
var queue = [(i, j)]
while !queue.isEmpty {
let v = queue.removeFirst()
for k in 0..<4 {
let nx = v.0 + dx[k]
let ny = v.1 + dy[k]
if !(0..<n ~= nx) || !(0..<m ~= ny) || copyBoard[nx][ny] == 1 {
continue
}
if copyBoard[nx][ny] == 0 {
queue.append((nx, ny))
copyBoard[nx][ny] = 2
}
}
}
}
makeWall(toPick: 3)
var maxArea = 0
for result in results {
copyBoard = board
copyBoard[result[0][0]][result[0][1]] = 1
copyBoard[result[1][0]][result[1][1]] = 1
copyBoard[result[2][0]][result[2][1]] = 1
for virus in virusLocation {
bfs(virus.0, virus.1)
}
maxArea = max(maxArea, safeArea())
}
print(maxArea)
๋ฐ์ํ
๋๊ธ
์ด ๊ธ ๊ณต์ ํ๊ธฐ
-
๊ตฌ๋
ํ๊ธฐ
๊ตฌ๋ ํ๊ธฐ
-
์นด์นด์คํก
์นด์นด์คํก
-
๋ผ์ธ
๋ผ์ธ
-
ํธ์ํฐ
ํธ์ํฐ
-
Facebook
Facebook
-
์นด์นด์ค์คํ ๋ฆฌ
์นด์นด์ค์คํ ๋ฆฌ
-
๋ฐด๋
๋ฐด๋
-
๋ค์ด๋ฒ ๋ธ๋ก๊ทธ
๋ค์ด๋ฒ ๋ธ๋ก๊ทธ
-
Pocket
Pocket
-
Evernote
Evernote