Skip to content

[Algorithm] DFS와 BFSΒ #168

Description

@hwangJi-dev

πŸ’¬Β λ¬Έμ œ

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


πŸ’¬Β Idea

  • DFSλ₯Ό μˆ˜ν–‰ν•  λ•Œ λ²ˆν˜Έκ°€ μž‘μ€ λ…Έλ“œλ“€λΆ€ν„° μˆœνšŒν•˜κΈ° μœ„ν•΄μ„œ 순회 배열을 μ •λ ¬ν•œ λ’€ λ’€μ§‘μ–΄μ„œ μ €μž₯ν•΄μ€€λ‹€.
  • BFSλ₯Ό μˆ˜ν–‰ν•  λ•Œλ„ λ²ˆν˜Έκ°€ μž‘μ€ λ…Έλ“œλ“€λΆ€ν„° μˆœνšŒν•˜κΈ° μœ„ν•΄μ„œ 순회 배열을 μ •λ ¬ν•˜μ—¬ μ €μž₯ν•΄μ€€λ‹€.

πŸ’¬Β ν’€μ΄

func solution1260(){letinfo=readLine()!.split(separator:"").map({Int(String($0))! })vargraph:[Int:[Int]]=[:]for_in0..<info[1]{letnodes=readLine()!.split(separator:"").map({Int(String($0))! })ifgraph[nodes[0]]==nil{graph[nodes[0]]=[nodes[1]]}else{graph[nodes[0]]?.append(nodes[1])}ifgraph[nodes[1]]==nil{graph[nodes[1]]=[nodes[0]]}else{graph[nodes[1]]?.append(nodes[0])}}func dfs(graph:[Int:[Int]], start:Int)->[Int]{varneedToVisitStack:[Int]=[start]varvisitedQueue:[Int]=[]while !needToVisitStack.isEmpty {letnode= needToVisitStack.removeLast()if visitedQueue.contains(node){continue}
visitedQueue.append(node)iflet nodes =graph[node]?.sorted().reversed(){
needToVisitStack += nodes
}}return visitedQueue
}func bfs(graph:[Int:[Int]], start:Int)->[Int]{varneedToVisitQueue:[Int]=[start]varvisitedQueue:[Int]=[]while !needToVisitQueue.isEmpty {letnode= needToVisitQueue.removeFirst()if visitedQueue.contains(node){continue}
visitedQueue.append(node)iflet nodes =graph[node]?.sorted(){
needToVisitQueue += nodes
}}return visitedQueue
}print(dfs(graph: graph, start:info[2]).map({String($0)}).joined(separator:""))print(bfs(graph: graph, start:info[2]).map({String($0)}).joined(separator:""))}

μ†Œμš”μ‹œκ°„ : 30λΆ„

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions