๋ฌธ์ :
https://www.acmicpc.net/problem/1389
๋ถ์ :
์ฒ์์๋ ์ ์ด๊ฒ BFS์ง ? ๊น์ด์ ๋ฐ๋ผ ๋ด๋ ค๊ฐ๋๊น๋ DFS ์๋๊ฐ ์ถ์๋ค. ํ์ง๋ง ๋ค์ ์๊ฐํด๋ณด๋ ์ฐ๋ฆฌ๋ ๊น์ด๊ฐ ๋ฎ์ ์น๊ตฌ ๊ด๊ณ๊ฐ ์๋ค๋ฉด ์ด ๊ฐ์ ๋ฐํํด์ผ ํ๋ค. ๋ฐ๋ผ์ ๊น์ด๊ฐ ๋ฎ์ ๊ณณ์ ์ํ๋ ์์๊ฐ ์๋ค๋ฉด visit๋ฅผ true๋ก ๋ง๋ค์ด ๋ ๊น์ ๊ณณ์ ์ํ๋ ์์๊ฐ ์์ด๋ ๋ฐฉ๋ฌธํ์ง ์๊ณ ๋์ด๊ฐ์ ์๊ฒ๋๋ค.
๋ํ ์๊ธฐ ์์ ์ ์ ์ธํ ๋ชจ๋ ์น๊ตฌ์ ๊ด๊ณ(๊น์ด)๋ฅผ ์๊ณ ์ถ์ ๊ฒ์ผ๋ก for๋ฌธ์ ๋๋ ์๊ธฐ ์์ ์ ๊น์ด๊ฐ 1์ธ ์น๊ตฌ๊ฐ ์๋ 1 ~ N๊น์ง ๋ชจ๋ ๊ฒ์ฌํด์ผ ํ๋ค. ์ด ์ ์ ์ฐธ๊ณ ํ์ฌ queue ์ธ์์ queue(start: Int, find: Int, cnt: Int) ๋ฅผ queue(start: Int, cnt: Int) ์์ ์์๋ง ์ ๋ฐ์ดํธ ๋๊ฒ๋ ์์ ํ์ฌ ํด๊ฒฐํ๋ค.
ํ๋ฆฐ ์ ๊ทผ ์ฝ๋ :
import Foundation
var line = readLine()!.split(separator: " ").map { Int(String($0))! }
var n = line[0]
var m = line[1]
var tree: [[Int]] = Array(repeating: [], count: n+1)
var visit: [Int] = Array(repeating: 0, count: n+1)
for _ in 0..<m {
var l = readLine()!.split(separator: " ").map { Int(String($0))! }
tree[l[0]].append(l[1])
tree[l[1]].append(l[0])
}
func bfs_level(start: Int, find: Int, cnt: Int) {
var queue = [(Int, Int, Int)]()
visit[start] = 1
queue.append((start, find, cnt))
while !queue.isEmpty {
let now = queue.first!.0
let value = queue.first!.1
let cn = queue.first!.2
queue.removeFirst()
if value > n { break }
if tree[now].contains(value) {
visit[value] = cn
queue.append((start, value+1, 1))
continue
}
for i in 0..<tree[now].count {
var next = tree[now][i]
if visit[next] == 0 {
queue.append((next, value, cnt+1))
}
}
}
}
Swift ์ฝ๋ :
//
// main.swift
// SOMA๐ฉ๐ป๐ป
//
// Created by JoSoJeong on 2022/04/17.
//
import Foundation
var line = readLine()!.split(separator: " ").map { Int(String($0))! }
var n = line[0]
var m = line[1]
var tree: [[Int]] = Array(repeating: Array(repeating: 0, count: n+1), count: n+1)
for _ in 0..<m {
let l = readLine()!.split(separator: " ").map { Int(String($0))! }
tree[l[0]][l[1]] = 1
tree[l[1]][l[0]] = 1
}
func bfs_level(start: Int, cnt: Int) -> Int {
var visit: [Bool] = Array(repeating: false, count: n+1)
var queue = [(Int, Int)]()
var answer = 0
visit[start] = true
queue.append((start, cnt))
while !queue.isEmpty {
let now = queue.first!.0
let cnt = queue.first!.1
queue.removeFirst()
for i in 1..<n+1 {
if !visit[i] && tree[now][i] == 1 {
answer += cnt
queue.append((i, cnt + 1))
visit[i] = true
}
}
}
return answer
}
var answer = 0
var min = 10000
for i in 1..<n {
let temp = bfs_level(start: i, cnt: 1)
if(temp < min) {
min = temp
answer = i
}
}
print(answer)
'Algorithm๐ฐ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] Swift 1504 ํน์ ํ ์ต๋จ ๊ฒฝ๋ก dijkstra (0) | 2022.04.18 |
---|---|
[๋ฐฑ์ค] Swift 14503 ๋ก๋ด ์ฒญ์๊ธฐ ์๋ฎฌ๋ ์ด์ , DFS (0) | 2022.04.18 |
[๋ฐฑ์ค] Swift 2302 ๊ทน์ฅ ์ข์ DP (0) | 2022.04.17 |
[๋ฐฑ์ค] Swift 1309 ๋๋ฌผ์ DP (0) | 2022.04.16 |
[๋ฐฑ์ค] 1049 Swift ๊ธฐํ์ค Greedy (0) | 2022.04.13 |
๋๊ธ