Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] (Swift) 11403๋ฒˆ - ๊ฒฝ๋กœ์ฐพ๊ธฐ (DFS๋กœ ํ’€๊ธฐ)

๊ฐ์ž ๐Ÿฅ” 2022. 9. 19. 16:46
๋ฐ˜์‘ํ˜•

๐ŸŸ  ๋ฌธ์ œ ๋งํฌ

https://www.acmicpc.net/problem/11403

 

11403๋ฒˆ: ๊ฒฝ๋กœ ์ฐพ๊ธฐ

๊ฐ€์ค‘์น˜ ์—†๋Š” ๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„ G๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋“  ์ •์  (i, j)์— ๋Œ€ํ•ด์„œ, i์—์„œ j๋กœ ๊ฐ€๋Š” ๊ฒฝ๋กœ๊ฐ€ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net

 

๐ŸŸ  ๋ฌธ์ œ ํ’€์ด

start์ง€์ ์„ ๊ธฐ์ค€์œผ๋กœ dfs๋ฅผ ๋Œ๋ ค์ค„ ๊ฒƒ์ด๋‹ค.
dfs๋Š” ๋‘๊ฐ€์ง€์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ „๋‹ฌ๋ฐ›์„ ๊ฑด๋ฐ, ์•ž๋ถ€๋ถ„์€ (์‹œ์ž‘ ํ–‰), ๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ๋Š” (ํ˜„์žฌ ๋ณด๊ณ ์žˆ๋Š”ํ–‰)์œผ๋กœ ๊ธฐ์–ตํ•˜๋ฉด๋œ๋‹ค. ๊ทธ๋ž˜์„œ ์ด๊ฒƒ์„ ๋Œ๋ ค์ฃผ๋ฉด, ์•„๋ž˜์ฒ˜๋Ÿผ ๋Œ์•„๊ฐ€๊ฒŒ ๋œ๋‹ค.

 

๐ŸŸ  ์ •๋‹ต ์ฝ”๋“œ

https://github.com/deslog/Algorithm/blob/main/Algorithm/Boj/11403_%EA%B2%BD%EB%A1%9C%EC%B0%BE%EA%B8%B0/main.swift

 

GitHub - deslog/Algorithm: โœจ ๋ฐฑ์ค€, ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Swift ๋ฌธ์ œํ’€์ด โœจ

โœจ ๋ฐฑ์ค€, ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Swift ๋ฌธ์ œํ’€์ด โœจ. Contribute to deslog/Algorithm development by creating an account on GitHub.

github.com

import Foundation

let n = Int(readLine()!)!
var graph = [[Int]]()
for i in 0..<n {
    graph.append(readLine()!.split(separator: " ").map { Int(String($0))! })
}
var visited = Array(repeating: false, count: n)
var result = Array(repeating: Array(repeating: 0, count: n), count: n)

func dfs(start: Int, now: Int) {
    for i in 0..<n {
        if graph[now][i] == 1 && !visited[i] {
            result[start][i] = 1
            visited[i] = true
            dfs(start: start, now: i)
        }
    }
}

for i in 0..<n {
    dfs(start: i, now: i)
    visited = Array(repeating: false, count: n)
}

for j in result {
    for r in j {
        print(r, terminator: " ")
    }
    print()
}

 

๋ฐ˜์‘ํ˜•