프로그래머스 LV2. 방문 길이
접근 방식
칸이 아니라 이동한 구간(간선)을 방문 단위로 잡는 문제. 좌표 하나만 저장하면 같은 칸에 서로 다른 방향에서 들어온 경우를 구분하지 못함.
처음에는 방문한 point = (x,y)만 저장했는데, (5,5)에서 (4,5)로 간 경우와 (4,4)에서 (4,5)로 간 경우가 도착 칸이 같아 구분되지 않음.
다음에는 시작점과 도착점을 한 묶음으로 저장. previousPoint, currentPoint를 (5,5,4,5)처럼 4-튜플로 들고 감. 이번엔 왕복이 문제였음. (4,5,5,5)와 (5,5,4,5)는 같은 구간을 반대로 지난 것인데 서로 다른 값이라 2번 저장됨. 테스트 케이스 "LRLR"의 정답은 1.
그래서 정방향 check와 역방향 check2를 함께 만들어, visited에 둘 중 하나라도 있으면 추가하지 않도록 함. 두 방향 어느 것도 없을 때만 append. 초기값 (5,5,5,5) 하나를 빼려고 마지막에 count - 1을 반환.
코드
//
// 49994.swift
// Algorithm
//
// Created by Hamlit Jason on 2022/04/16.
//
//https://programmers.co.kr/learn/courses/30/lessons/49994
import Foundation
struct p49994 {
static func run() {
// print(p49994.solution("LULLLLLLU")) // 7
// print(p49994.solution("ULURRDLLU")) // 7
// print(p49994.solution("UUUUDUDUDUUU")) // 5
print(p49994.solution("LRLR")) // 1
}
static func solution(_ dirs:String) -> Int {
var visited: [(Int, Int, Int, Int)] = [(5,5,5,5)] // (x,y) 시작점 -> (x,y) 끝점 루트 자체를 저장하자.
var previousPoint = (5,5)
var currentPoint = (5,5)
var x = currentPoint.0
var y = currentPoint.1
for dir in dirs {
switch dir {
case "U":
if y - 1 < 0 { // 판을 넘어가면
continue
} else {
y -= 1
}
break
case "L":
if x - 1 < 0 {
continue
} else {
x -= 1
}
break
case "R":
if x + 1 > 10 {
continue
} else {
x += 1
}
break
case "D":
if y + 1 > 10 {
continue
} else {
y += 1
}
break
default: print("Default")
}
currentPoint = (x,y)
let check = (previousPoint.0, previousPoint.1, currentPoint.0, currentPoint.1)
let check2 = (currentPoint.0, currentPoint.1, previousPoint.0, previousPoint.1)
previousPoint = currentPoint
if !visited.contains(where: {
return $0 == check || $0 == check2
}) {
visited.append(check)
}
}
print(visited)
return visited.count - 1
}
}'알고리즘 문제 풀이' 카테고리의 다른 글
| [Swift] 프로그래머스 LV2. 수식 최대화 (0) | 2022.04.16 |
|---|---|
| [Swift] 프로그래머스 LV2. [3차] 파일명 정렬 (0) | 2022.04.16 |
| [Swift] 프로그래머스 LV2. 주차 요금 계산 (0) | 2022.04.16 |
| [Swift] 프로그래머스 LV2. 큰 수 만들기 (4) | 2022.04.13 |
| [Swift] 프로그래머스 LV2. 쿼드 압축 후 개수 세기 (0) | 2022.04.13 |