[프로그래머스/Swift] 방문 길이
https://school.programmers.co.kr/learn/courses/30/lessons/49994
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
Swift로 언어를 바꾸고 광명 찾았습니다..
Swift야 내가 항상 사랑한다.
Set를 사용해서 간단하게 풀 수 있는 구현문제! 한 20분 만에.. 풀었나?
우선 상하좌우 이동, 경계를 벗어나는 명령일 경우 무시, 갔던 곳이면 answer 값 증가하지 않음.
그리고 이게 칸으로 이동하는게 아니라 좌표점으로 이동하는 것이기 때문에 사용할 변수가 늘어났다.
시작점(x, y)과 도착점(x, y)에 대한 값을 구조체로 만들어줬다.
그리고 setRoad라는 Array Collection으로 갔던 곳을 넣어줬다.
(처음에 set으로 했다가 array로 틀었다. 어차피 중복(갔던 길)이면 넣지 않으니까...ㅎ)
그리고 checkOutOfRange (경계를 벗어났는지 [-5,5])와 checkVisited()를 함수로 만들어서 구현했다.
경계를 벗어났으면 명령 무시하고 (guard 문으로 빨리 탈출하게 했다)
만약 처음 가는 곳이라면 answer 증가, setRoad에 길을 추가해 준다.
그리고 갔던 길이든 안 갔던 길이든 현재 좌표값을 변경해 준다. (currentCoordinate)
-> 여기서 갔던 곳이라는 건 반대로 이동했을 때도 적용되므로 start점과 end점을 반대로 뒤집어서도 체크해줘야 한다.
import Foundation
/*
상하좌우로 한칸씩 이동. (0,0)에서 시작. 최대 (-5,5)
캐릭터가 지나간 길 중 캐릭터가 처음 걸어본 길의 길이 구하기
경계를 넘어선 명령은 무시
*/
struct RoadCoordinate: Hashable {
let sx, sy, ex, ey : Int
}
func solution(_ dirs:String) -> Int {
var answer = 0
var currentCoordinate = (0, 0) //tuple x, y
var setRoad = Array<RoadCoordinate>()
//경계안에 있는지 체크
func checkOutOfRange(endX: Int, endY: Int) -> Bool {
return (-5...5) ~= endX && (-5...5) ~= endY ? true : false
}
//갔던 곳인지 체크
func checkVisited(endX: Int, endY: Int) -> Bool {
return setRoad.contains(RoadCoordinate(sx: currentCoordinate.0, sy: currentCoordinate.1, ex: endX, ey: endY)) || setRoad.contains(RoadCoordinate(sx: endX, sy: endY, ex: currentCoordinate.0, ey: currentCoordinate.1)) ? true : false
}
for dir in dirs {
var endX = currentCoordinate.0
var endY = currentCoordinate.1
switch dir {
case "U": endX -= 1 //-1, 0
case "D": endX += 1 // 1, 0
case "R": endY += 1 // 0, 1
case "L": endY -= 1 // 0, -1
default: break
}
guard checkOutOfRange(endX: endX, endY: endY) else { continue } //범위를 넘어서면 명령 패스
if !checkVisited(endX: endX, endY: endY) {
answer += 1
setRoad.append(RoadCoordinate(sx: currentCoordinate.0, sy: currentCoordinate.1, ex: endX, ey: endY))
}
currentCoordinate = (endX, endY) //current coordinate update
}
return answer
}
프로그래머스는 이렇게 보여줘서 더 쾌감이...
역시 파란색은 최고야~