Skip to content

[Algorithm] 2606 - 바이러스 #166

Description

@hwangJi-dev

💬 문제

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


💬 Idea

  • 양방향 그래프를 만든 뒤 DFS 탐색을 하여 1번 컴퓨터와 연결된 리스트를 구한다.
  • 1번 컴퓨터를 제외한 감염 컴퓨터 수를 출력한다

💬 풀이

import Foundation
func solution2606()->Int{letcomputerCount=Int(readLine()!)!
letconnectCount=Int(readLine()!)!
vargraph:[String:[String]]=[:]for_in0..<connectCount {letconnect=readLine()!.split(whereSeparator:{ $0 ==""}).map({String($0)})letnode1=connect[0]letnode2=connect[1]ifgraph[node1]==nil{graph[node1]=[node2]}else{graph[node1]?.append(node2)}ifgraph[node2]==nil{graph[node2]=[node1]}else{graph[node2]?.append(node1)}}letwarmVirusComputerArr=dfs(graph,"1")return warmVirusComputerArr.count -1}func dfs(_ graph:[String:[String]], _ start:String)->[String]{varneedToVisitStack:[String]=[start]varvisitedQueue:[String]=[]while !needToVisitStack.isEmpty {letnode= needToVisitStack.removeLast()if visitedQueue.contains(node){continue}
visitedQueue.append(node)
needToVisitStack +=graph[node]??[]}return visitedQueue
}

소요시간 : 25분

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