1.
import Foundation
func solution(_ park:[String], _ routes:[String]) -> [Int] {
var currentY = 0
var currentX = 0
var obstacles: [(Int,Int)] = []
for (y,value) in park.enumerated() {
for (x, value2) in value.map({ String($0) }).enumerated() {
if value2 == "S" {
currentX = x
currentY = y
} else if value2 == "X" {
obstacles.append((y, x))
}
}
}
for route in routes {
let tmp = route.split(separator: " ").map { String($0) }
let direction = tmp[0]
let distance = Int(tmp[1])!
var tmpY = currentY
var tmpX = currentX
var isValid = true
for _ in 1...distance {
if direction == "E" {
tmpX += 1
} else if direction == "W" {
tmpX -= 1
} else if direction == "S" {
tmpY += 1
} else if direction == "N" {
tmpY -= 1
}
if tmpY < 0 || tmpY >= park.count || tmpX < 0 || tmpX >= park[0].count || obstacles.contains(where: { $0 == (tmpY, tmpX) }) {
isValid = false
break
}
}
if isValid {
currentY = tmpY
currentX = tmpX
}
}
return [currentY, currentX]
}
2.
import Foundation
func solution(_ park:[String], _ routes:[String]) -> [Int] {
var currentY = 0
var currentX = 0
var obstacles = Set<[Int]>()
for (y,value) in park.enumerated() {
for (x, value2) in value.enumerated() {
if value2 == "S" {
currentX = x
currentY = y
} else if value2 == "X" {
obstacles.insert([y,x])
}
}
}
let directionMap = ["E": (0, 1), "W": (0, -1), "S": (1, 0), "N": (-1, 0)]
for i in routes {
let tmp = i.split(separator: " ")
let direction = String(tmp[0])
let distance = Int(tmp[1])!
let (dy, dx) = directionMap[direction]!
var newY = currentY
var newX = currentX
var isBlocked = false
print(direction, distance, "current State: \(currentY), \(currentX)")
for _ in 1...distance {
newY += dy
newX += dx
// 범위 벗어나거나 장애물 만나는 경우
if newY < 0 || newY >= park.count || newX < 0 || newX >= park[0].count || obstacles.contains([newY, newX]) {
isBlocked = true
break
}
}
if !isBlocked {
currentY = newY
currentX = newX
}
}
return [currentY, currentX]
}
'Algorithm > programmers' 카테고리의 다른 글
프로그래머스 - 로또의 최고 순위와 최저 순위 (0) | 2024.09.11 |
---|---|
프로그래머스 - 바탕화면 정리 (0) | 2024.09.10 |
프로그래머스 - 약수의 개수와 덧셈 (0) | 2024.09.09 |
프로그래머스 - 숫자 짝꿍 (0) | 2024.09.09 |
프로그래머스 - 369게임 feat. Regex 지원안될 때 정규표현식 (1) | 2024.09.07 |