๋ฌธ์
ํ์ด ์ธ์ด
Kotlin
์ฝ๋
import java.util.*
class Solution {
fun solution(places: Array<Array<String>>): IntArray {
val answer = mutableListOf<Int>()
val size = places.size
for (place in places) {
var check = 0
for (i in 0 until size) {
for (j in 0 until size) {
if (place[i][j] == 'P') {
if (bfs(place, i, j, size).not()) {
check = 1
break
}
}
}
if (check == 1) {
break
}
}
if (check == 1) answer.add(0)
else answer.add(1)
}
return answer.toIntArray()
}
fun bfs(place: Array<String>, src_x: Int, src_y: Int, size: Int): Boolean {
val queue = LinkedList<Array<Int>>()
var visited = Array(size) { IntArray(size) { 0 } }
val dx = arrayOf(0, 0, 1, -1)
val dy = arrayOf(1, -1, 0, 0)
queue.add(arrayOf(src_x, src_y, 0)) // x, y, ๊ฑฐ๋ฆฌ
visited[src_x][src_y] = 1
while (queue.isNotEmpty()) {
val element = queue.poll()
val x = element[0]
val y = element[1]
val dist = element[2]
if (dist >= 3) return true
else if (dist != 0 && place[x][y] == 'P') return false
for (i in 0..3) {
val nx = x + dx[i]
val ny = y + dy[i]
val nd = dist + 1
if (nx in 0 until size && ny in 0 until size) {
if (place[nx][ny] != 'X' && visited[nx][ny] == 0) {
queue.add(arrayOf(nx, ny, nd))
visited[nx][ny] = 1 // ํด๋น์ง์ ๋ฐฉ๋ฌธ
}
}
}
}
return true
}
}
ํ์ด ๋ฐฉ๋ฒ
๋ฉด์ ์๊ฐ ์์ ์๋ ๊ณณ์์ BFS
๋ฅผ ์งํํ๋ค. ์ด ๋ ๊ฑฐ๋ฆฌ๊ฐ 3๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ ๊ฒฝ์ฐ ๊ฑฐ๋ฆฌ๋๊ธฐ
๊ฐ ์ ๋๋ก ๋์ด ์๋ ์ํ์ด๋ฏ๋ก true
๋ฅผ ๋ฆฌํดํ๋ค. ๊ฑฐ๋ฆฌ๊ฐ 3๋ณด๋ค ์๊ณ ํด๋น ์ขํ์ ๋ฉด์ ์๊ฐ ์์ ์๋ ๊ฒฝ์ฐ ๊ฑฐ๋ฆฌ๋๊ธฐ
๊ฐ ์ ๋๋ก ๋์ด ์์ง ์์ ์ํ์ด๋ฏ๋ก false
๋ฅผ ๋ฆฌํดํ๋ค. ๋ ๊ฐ์ง ์กฐ๊ฑด์ ํด๋นํ์ง ์๋ ๊ฒฝ์ฐ์๋ ๋ค์ ์ด๋ํ ์ขํ๋ฅผ ํ์ํ๋ค.
๊ฒฐ๊ณผ
'โ๏ธ ์ฝํ ์ค๋น > DFS, BFS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[DFS์ BFS] [Python / C++] 1260. DFS์ BFS (0) | 2021.04.18 |
---|---|
[DFS์ BFS] [Python / C++] 1707. ์ด๋ถ ๊ทธ๋ํ (0) | 2021.04.14 |
[DFS์ BFS] [Python / C++] 7562. ๋์ดํธ์ ์ด๋. (0) | 2021.04.13 |
[DFS์ BFS] [Python / C++] 2206. ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ. (0) | 2021.04.12 |