-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
💬 문제
https://school.programmers.co.kr/learn/courses/30/lessons/81302?language=swift
💬 Idea
- 맨해튼 거리가 2 이하인 조건에 부합하는 경우라면 0을, 그렇지 않다면 1을 반환해주자.
<맨해튼 거리가 2 이하인 조건>
인덱스 (y, x)에 P가 있다고 할 때
- 같은 row(행)에 거리가 2 이하인 곳에 P가 있을 때
- 거리가 1인곳에 P가 있다면 파티션 체크할 필요 없이 false
- 거리가 2인 곳이라면
- 가운데에 파티션이 있는지 체크하고 없다면 false
- 같은 col(열)에 거리가 +- 2 이하인 곳에 P가 있을 때
- 위와 동일
- 좌상 좌하 우상 우하 대각선에 P가 있을 때
- P X
X P - X P
P X - 해당 2개의 형태가 아니라면 false
- P X
💬 풀이
import Foundation
func solution(_ places:[[String]]) -> [Int] {
var ans: [Int] = []
for i in places {
var placeArr: [[String]] = []
i.forEach({ placeArr.append(Array($0).map({ String($0) })) })
var isRightDistance = true
for (iIdx, i) in placeArr.enumerated() {
for (jIdx, j) in i.enumerated() {
if j == "P" {
if !findIfDiaKeepDistance((iIdx, jIdx), placeArr) || !findIfColKeepDistance((iIdx, jIdx), placeArr) || !findIfRowKeepDistance((iIdx, jIdx), placeArr) {
isRightDistance = false
break
}
}
}
}
ans.append(isRightDistance ? 1 : 0)
}
return ans
}
// Row (Int, Int)에서 0: y, 1: x
func findIfRowKeepDistance(_ idx: (Int, Int), _ places: [[String]]) -> Bool {
// 사이에 X 벽이 있을 수 없음
if idx.1 + 1 <= 4 {
if places[idx.0][idx.1 + 1] == "P" { return false }
}
if idx.1 - 1 >= 0 {
if places[idx.0][idx.1 - 1] == "P" { return false }
}
if idx.1 + 2 <= 4 {
if places[idx.0][idx.1 + 2] == "P" && places[idx.0][idx.1 + 1] != "X" { return false }
}
if idx.1 - 2 >= 0 {
if places[idx.0][idx.1 - 2] == "P" && places[idx.0][idx.1 - 1] != "X" { return false }
}
return true
}
// Column
func findIfColKeepDistance(_ idx: (Int, Int), _ places: [[String]]) -> Bool {
// 사이에 X 벽이 있을 수 없음
if idx.0 + 1 <= 4 {
if places[idx.0 + 1][idx.1] == "P" { return false }
}
if idx.0 - 1 >= 0 {
if places[idx.0 - 1][idx.1] == "P" { return false }
}
if idx.0 + 2 <= 4 {
if places[idx.0 + 2][idx.1] == "P" && places[idx.0 + 1][idx.1] != "X" { return false }
}
if idx.0 - 2 >= 0 {
if places[idx.0 - 2][idx.1] == "P" && places[idx.0 - 1][idx.1] != "X" { return false }
}
return true
}
// Diagonal
func findIfDiaKeepDistance(_ idx: (Int, Int), _ places: [[String]]) -> Bool {
if idx.0 + 1 <= 4 && idx.1 + 1 <= 4 {
// 우하
if places[idx.0 + 1][idx.1 + 1] == "P" {
if places[idx.0][idx.1 + 1] != "X" || places[idx.0 + 1][idx.1] != "X" {
return false
}
}
}
if idx.0 - 1 >= 0 && idx.1 - 1 >= 0 {
// 좌상
if places[idx.0 - 1][idx.1 - 1] == "P" {
if places[idx.0 - 1][idx.1] != "X" || places[idx.0][idx.1 - 1] != "X" {
return false
}
}
}
if idx.0 + 1 <= 4 && idx.1 - 1 >= 0 {
// 좌하
if places[idx.0 + 1][idx.1 - 1] == "P" {
if places[idx.0][idx.1 - 1] != "X" || places[idx.0 + 1][idx.1] != "X" {
return false
}
}
}
if idx.0 - 1 >= 0 && idx.1 + 1 <= 4 {
// 우상
if places[idx.0 - 1][idx.1 + 1] == "P" {
if places[idx.0 - 1][idx.1] != "X" || places[idx.0][idx.1 + 1] != "X" {
return false
}
}
}
return true
}
소요시간
: 1시간 30분