Skip to content

[Algorithm] 트리의 부모 찾기 #169

Description

@hwangJi-dev

💬 문제

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


💬 Idea

  • 트리의 부모를 찾기 위해서 다음 순회할 노드들을 저장해줄 때 visited 배열에 해당 인덱스의 부모를 저장해주었다.

💬 풀이

func solution11725(){vargraph:[Int:[Int]]=[:]letN=Int(readLine()!)!
for_in1..<N {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])}}varvisited=Array(repeating:0, count: N +1)func dfs(graph:[Int:[Int]], start:Int){iflet nodes =graph[start]{foriin nodes {ifvisited[i]==0{visited[i]= start
dfs(graph: graph, start: i)}}}}dfs(graph: graph, start:1)foriin2...N {print(visited[i])}}

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