문제: https://programmers.co.kr/learn/courses/30/lessons/81302#fn1
코딩테스트 연습 - 거리두기 확인하기
[["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]] [1, 0, 1, 1, 1]
programmers.co.kr
1. original(P가 있던 곳)과 현재 있는 지점을 비교합니다.
2. 맨하튼 거리가 2이고 둘이 수직/수평으로 있을 때 사이에 파티션이 있는지 확인합니다. 파티션이 없다면 result를 업데이트하고 파티션이 있다면 거리두기가 지켜진 것이기에 업데이트하지 않습니다.
import Foundation
let dx = [-1, 1, 0, 0]
let dy = [0, 0, -1, 1]
func solution(_ places:[[String]]) -> [Int] {
var result = Array(repeating: 1, count: places.count)
func dfs(visited: inout [[Bool]], original: [Int], current: [Int], place: Int) {
if result[place] == 0 { return }
let x = current[0]
let y = current[1]
visited[x][y] = true
for i in 0...3 {
let nx = x + dx[i]
let ny = y + dy[i]
if nx < 0 || ny < 0 || nx >= 5 || ny >= 5 { continue }
if visited[nx][ny] { continue }
if Array(places[place][nx])[ny] == "X" { continue }
if Array(places[place][nx])[ny] == "P" {
let xdiff = abs(original[0] - nx)
let ydiff = abs(original[1] - ny)
if xdiff + ydiff <= 2 {
if xdiff == 2 && ydiff == 0 { // x가 두칸 떨어져있고
if nx < original[0] {
if Array(places[place][nx + 1])[ny] == "X" {
continue
}
} else {
if Array(places[place][nx - 1])[ny] == "X" {
continue
}
}
}
if xdiff == 0 && ydiff == 2 { // y가 두칸 떨어져있고
if ny < original[1] {
if Array(places[place][nx])[ny + 1] == "X" {
continue
}
} else {
if Array(places[place][nx])[ny - 1] == "X" {
continue
}
}
}
result[place] = 0
return
}
} else {
dfs(visited: &visited, original: original, current: [nx, ny], place: place)
}
}
}
for place in 0..<places.count {
var visited = Array(repeating: Array(repeating: false, count: 5), count: 5)
for i in 0...4 {
let row = Array(places[place][i])
for j in 0...4 {
if row[j] == "P" {
dfs(visited: &visited, original: [i, j], current: [i, j], place: place)
}
}
}
}
return result
}
solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]]) // [1, 0, 1, 1, 1]
'알고리즘' 카테고리의 다른 글
[Swift] 프로그래머스 - 카카오 튜플 (0) | 2022.02.11 |
---|---|
[Swift] 프로그래머스 - 카카오 수식 최대화 (0) | 2022.02.11 |
[Swift] 프로그래머스 - 카카오 뉴스 클러스터링 (0) | 2022.02.10 |
[Swift] 프로그래머스 - 짝지어 제거하기 (0) | 2022.02.10 |
[Swift] 프로그래머스 - 카카오 크레인 인형뽑기 게임 (0) | 2022.02.10 |
댓글