๋ฐ์ํ
๐ป ๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/7576
๐ป ํ์ด
BFS๋ก ํ์๋ค. ์ฌ์ค ์์์ ์ด ์ฌ๋ฌ๊ฐ์ธ BFS๋ ์ด๋ป๊ฒ ํ์ด์ผํ ์ง ๋ชจ๋ฅด๊ฒ ์ด์, ์ธํฐ๋ท์ ์ฐธ๊ณ ํด์ ํ์๋คใ ใ
- m๊ณผ n์ ์ ๋ ฅ๋ฐ๋๋ค.
- 0, -1, 1์ด ๋ค์ด์๋ ๋ฐฐ์ด์ box๋ก ์ ๋ ฅ๋ฐ์๋ค.
- day๋ ๋ฉฐ์น ์ด ์ง๋ฌ๋์ง ํ๋จํ๊ธฐ ์ํด์ ๋ง๋ ๋ฐฐ์ด์ด๋ค. ๋ค์์ ๋ณด๋ฉด ํ์นธํ์นธ ์ต์ด๋๊ฐ๋๋ง๋ค +1 ์ ํด์ค๋ค.
let mn = readLine()!.split(separator: " ").map { Int(String($0))! }
let m = mn[0]
let n = mn[1]
var box = [[Int]]()
for _ in 0..<mn[1] {
let temp = readLine()!.split(separator: " ").map{Int(String($0))!}
box.append(temp)
}
var day = Array(repeating: Array(repeating: 0, count: 1001), count: 1001)
- dx, dy ์ํ์ข์ฐ๋ก ๋ฐฉํฅํค๋ฅผ ์ค์ ํ๋ค.
- queue๋ฅผ ์ฌ์ฉํด์ bfs๋ก ๋๋ ค์ค ๊ฒ์ด๋ค.
- lastIdx๋ ์ ๋ ฅ๋ฐ๋ ์ด์ ๊ฐ, ๊ฐ์ฅ ๋ง์ง๋ง์ ๋ฐฉ๋ฌธํ idx์ธ๊ฒฝ์ฐ, ๋ง์ง๋ง ๋ ๋ฐฉ๋ฌธํ ์ธ๋ฑ์ค๋ผ๋ ์๋ฏธ์ด๋ฏ๋ก, ์ ์ฅํด๋์๋ค๊ฐ ๋ง์ง๋ง์ ์ถ๋ ฅํ ๋ ์ฌ์ฉํด์ค ๊ฒ์ด๋ค.
- idx๋ 0๋ถํฐ ์์ํ๋ค. ์๋ removeFirst๋ฅผ ์ฌ์ฉํด์ queue์ popํด์ ๋ฃ์ด์ฃผ๋ ค๊ณ ํ๋๋ฐ, ์ด๋ ๊ฒ ํ๊ฒ๋๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ ํ๋ฅ ์ด ์ปค์ idx๋ฅผ ์ฌ์ฉํด๋ณธ๋ค.
- isCooked ์ต์ ํ ๋งํ ๊ฐ ์๋ ์๋๋ฅผ ๋ฐ์ง๋ ์ฌ์ฉํ ๊ฒ์ด๋ค.
let dx = [0, 0, -1, 1]
let dy = [-1, 1, 0, 0]
var queue = [[Int]]()
var lastIdx = [0, 0]
var idx = 0
var isCooked = true
- ๋จผ์ queue์๋ค๊ฐ ์ต์ ํ ๋งํ ๋ค์ ๋ฃ์ด์ค๋ค. ์ด ๊ณผ์ ์ด ์กฐ๊ธ ํท๊ฐ๋ ธ๋๋ฐ, ์์์ ์ด ์ฌ๋ฌ๊ฐ์ด๋ฏ๋ก ์ฌ๋ฌ๊ฐ ๋ฃ๊ณ ์์ํด์ฃผ๋ฉด ๋๋ค๊ณ ์ดํดํ์.
for i in 0..<n {
for j in 0..<m {
if box[i][j] == 1 {
queue.append([i, j])
}
}
}
- bfsํจ์๋ฅผ ๋ง๋ ๋ค.
- bfsํจ์์์๋ queue์ ์๋ณด๋ค, ์ธ๋ฑ์ค ์๊ฐ ๋ ์์๋๊น์ง ๋๋ฆฐ๋ค.
func bfs() {
while idx < queue.count {
let pop = queue[idx]
idx += 1
for k in 0..<4 {
let nx = pop[0] + dx[k]
let ny = pop[1] + dy[k]
if nx >= 0 && nx < n && ny >= 0 && ny < m {
if box[nx][ny] == 0 {
box[nx][ny] = 1
queue.append([nx, ny])
day[nx][ny] = day[pop[0]][pop[1]] + 1
lastIdx = [nx, ny]
}
}
}
}
}
bfs()
- ์ฌ๊ธฐ์์ค์ํ๋ ๊ฐ๋ , ์ต์ ํ ๋งํ ๊ฐ ํ๋๋ผ๋ ์์ผ๋ฉด ์๋๊ธฐ ๋๋ฌธ์ ์ต์๋์ง ํ๋ณํ ํ์ ์ถ๋ ฅํด์ค๋ค.
for i in 0..<n {
for j in 0..<m {
if box[i][j] == 0 {
isCooked = false
}
}
}
if isCooked {
print(day[lastIdx[0]][lastIdx[1]])
} else {
print(-1)
}
๐ป ์์ค์ฝ๋
let mn = readLine()!.split(separator: " ").map { Int(String($0))! }
let m = mn[0]
let n = mn[1]
var box = [[Int]]()
var day = Array(repeating: Array(repeating: 0, count: 1001), count: 1001)
for _ in 0..<mn[1] {
let temp = readLine()!.split(separator: " ").map{Int(String($0))!}
box.append(temp)
}
let dx = [0, 0, -1, 1]
let dy = [-1, 1, 0, 0]
var queue = [[Int]]()
var lastIdx = [0, 0]
var idx = 0
var isCooked = true
for i in 0..<n {
for j in 0..<m {
if box[i][j] == 1 {
queue.append([i, j])
}
}
}
func bfs() {
while idx < queue.count {
let pop = queue[idx]
idx += 1
for k in 0..<4 {
let nx = pop[0] + dx[k]
let ny = pop[1] + dy[k]
if nx >= 0 && nx < n && ny >= 0 && ny < m {
if box[nx][ny] == 0 {
box[nx][ny] = 1
queue.append([nx, ny])
day[nx][ny] = day[pop[0]][pop[1]] + 1
lastIdx = [nx, ny]
}
}
}
}
}
bfs()
for i in 0..<n {
for j in 0..<m {
if box[i][j] == 0 {
isCooked = false
}
}
}
if isCooked {
print(day[lastIdx[0]][lastIdx[1]])
} else {
print(-1)
}
๋ฐ์ํ