9019 swift - DSLR

2023. 3. 3. 15:39🐣/BOJ

사용 알고리즘 BFS

 

[Swift] Breadth-First Search / BFS

BFS (Breadth-First Search) 인접한 노드를 먼저 탐색하는 방식. O(Vertex+Edge) A→B→C→D→E→F→G→H 해당하는 그래프는 아래와 같이 인접 리스트로 나타낼 수 있다. let graph: [String: [String]] = [ "A" : ["B", "C"],

chanhhh.tistory.com

사용 자료구조 Queue

 

[Swift] (자료구조) 큐 / Queue

import Foundation class Queue { var enQueue: [T] = [] var deQueue: [T] = [] var count: Int { return enQueue.count + deQueue.count } var isEmpty: Bool { return enQueue.isEmpty && deQueue.isEmpty } init() { } func push(_ element: T) { enQueue.append(element)

chanhhh.tistory.com

사용 문법 Closure

 

개발자 찬히히

 

chanhhh.tistory.com

 

//
//  9019_DSLR.swift
//  swift_practise
//
//  Created by Chan on 2023/03/03.
//
//	https://www.acmicpc.net/problem/9019
//
//	MARK: - BFS

func D(_ n: Int) -> Int { (n * 2) % 10000 }
func S(_ n: Int) -> Int { n == 0 ? 9999 : n - 1 }
func L(_ n: Int) -> Int { (n % 1000) * 10 + n / 1000 }
func R(_ n: Int) -> Int { (n % 10) * 1000 + n / 10 }

var r = Int(readLine()!)!
for _ in 0..<r {
	var visited: [Bool] = Array(repeating: false, count: 10001)
	var q: [(Int, String)] = []
	var index = 0
	let AB = readLine()!.split(separator: " ").map{Int(String($0))!}
	let (A, B) = (AB[0], AB[1])
	q.append((A, ""))
	visited[A] = true
	
	while true {
		let select = q[index]
		let start = select.0, end = B, result = select.1
		index += 1
		if start != end {
			let d = D(start)
			let s = S(start)
			let l = L(start)
			let r = R(start)
			if visited[d] == false {
				visited[d] = true
				q.append((d, result + "D"))
			}
			if visited[s] == false {
				visited[s] = true
				q.append((s, result + "S"))
			}
			if visited[l] == false {
				visited[l] = true
				q.append((l, result + "L"))
			}
			if visited[r] == false {
				visited[r] = true
				q.append((r, result + "R"))
			}
		} else {
			print(result)
			break
		}
	}
}

'🐣 > BOJ' 카테고리의 다른 글

9935 swift - 문자열 폭발  (0) 2024.02.02
9663 swift - N-Queen  (0) 2023.06.12
11444 swift - 피보나치 수 6  (0) 2023.06.11
11521 swift - Boggle  (0) 2023.04.05
6186 swift - Best Grass  (1) 2023.02.27