-
[백준] (Swift) 1697번: 숨바꼭질 - BFS 문제Algorithm 2022. 5. 9. 16:51
1697번: 숨바꼭질
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일
www.acmicpc.net
import Foundation // 입력값 let input = readLine()!.split { $0 == " " }.map { Int(String($0))! } // 최대 범위 let max = 100000 // 초기 입력값 let currentLocation = input[0] let targetLocation = input[1] // return 해줄 값 var result = 0 // 두 입력값의 값이 같다면 종료한다 if currentLocation == targetLocation{ print(result) } else { // 방문한 노드들에 대해 위치와 소요한 시간을 기록한다 var queue: [(location: Int, sec: Int)] = [(currentLocation, 0)] // 방문한 위치에 대한 값을 [Bool] 로 저장한다 var visited: [Bool] = Array(repeating: false, count: max + 1) // 탐색 횟수 var index = 0 // 현재 위치는 이미 방문한 것으로 간주한다 visited[currentLocation] = true while index < queue.count{ // 현재 위치 let node = queue[index] // 탐색 횟수를 더해준다 index += 1 // 현재 위치에서 3가지 조건에 맞는 위치를 방문 한다 (총 3번 방문) for i in 0..<3{ // 방문할 위치 var next: Int switch i { // 1. 현재 위치에서 - 1 case 0: next = node.location - 1 // 2. 현재 위치에서 + 1 case 1: next = node.location + 1 // 3. 현재 위치에서 * 2 default: next = node.location * 2 } // 다음에 이동할 위치가 타겟과 일치할 경우 if next == targetLocation { // 결괏값에 다음위치(== 타겟)까지 가는 동안 소요된 시간을 넣어준다 result = node.sec + 1 // while 문을 멈춰주기 위한 장치 index = queue.count // break에 부딪힌다면 while 문 벗어나고 아래 print(result)가 실행될 것이다 break } else { // 다음 이동할 위치가 타겟과 동일하지 않을 경우 실행되는 실행문 // // 1. 음수일 경우 // 2. 범위를 초과한 경우 // 3. 이미 방문한 노드일 경우 // 위 조건 중 하나라도 만족한다면 while 처음으로 돌아간다 // if next < 0 || next > max || visited[next]{ continue } // 위 조건을 만족하지 않는다면 // 방문한 node로 기록한다 visited[next] = true // Queue에 추가해준다 queue.append((next, node.sec + 1)) } } } // while 문이 끝나고 결과를 return 해 준다 print(result) }
'Algorithm' 카테고리의 다른 글
[Leetcode] 1578. Minimum Time to Make Rope Colorful - Swift 1차 시도 (탈락) (0) 2022.12.30 [Leetcode] 1375. Number of Times Binary String Is Prefix-Aligned - Swift (통과) (0) 2022.12.30 [Programmers] 정렬 : 가장 큰 수 (0) 2022.01.27 [Programmers] 정렬 : K번째수 (0) 2022.01.27 [Programmers/ Python] 로또의 최고 순위와 최저 순위 (0) 2021.11.30