class `81302거리두기확인하기` {
var direction = arrayOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))
fun solution(places: Array<Array<String>>): IntArray {
val answer = ArrayList<Int>()
places.forEach { place ->
// P의 위치를 찾는 포문
var check = 1
for (i in 0..4) {
for (j in 0..4) {
if (place[i][j].equals('P')) {
if (!find(place, i, j)) {
check = 0
break
}
}
}
if (check == 0) {
break
}
}
answer.add(check)
}
answer.forEach{ println(it)}
return answer.toIntArray()
}
fun find(place: Array<String>, nowy: Int, nowx: Int): Boolean {
var check = true
for (i in 0..3) {
val newx = nowx + direction[i].second
val newy = nowy + direction[i].first
if (0 <= newx && newx < 5 && 0 <= newy && newy < 5) {
if (place[newy][newx].equals('X')) continue
if (place[newy][newx].equals('P')) {
check = false
break
} else {
for (j in 0..3) {
val newx2 = newx + direction[j].second
val newy2 = newy + direction[j].first
if (newx2 == nowx && newy2 == nowy) {
continue
}
if (0 <= newx2 && newx2 < 5 && 0 <= newy2 && newy2 < 5) {
if (place[newy2][newx2].equals('X')) continue
if (place[newy2][newx2].equals('P')) {
check = false
break
}
}
}
}
}
if (!check) {
break
}
}
return check
}
}
이 문제는 코딩테스트 당일에 못풀었던 문제다.
ㅎㅎ.. 이번에도 2틀동안 거쳐서 풀었다.
자꾸 Bfs를 하려고 했다. depth가 2일경우 return 하는 형식으로 처음에 짰다.
잘 안되어서 그냥 포문을 계속 돌리도록 짰는데, 결국 실수는 'X'를 체크안해준 곳에서 나왔다.
'X'를 체크해주니 깔끔하게 실행됐다.
만약에 맨하탄 거리 2정도, 즉 많은 거리를 체크하지 않는 경우 포문으로 도는것도 나쁘지 않은 것 같다.