ProgrammersLv3네트워크
문제
풀이 DFS
코드
visited = []
def DFS(node,computers):
for x in range(len(computers[node])):
if x != node and computers[node][x]==1 and x not in visited:
visited.append(x)
DFS(x,computers)
def solution(n, computers):
answer = 0
for i in range(n):
if i not in visited:
answer+=1
visited.append(i)
DFS(i,computers)
return answer
BFS 기억 잘 안나서 BFS로도 다시 풀어보기
from collections import deque
def BFS(node,computers,visited,n):
visited.append(node)
haveToVisit = deque([])
haveToVisit.append(node)
while haveToVisit:
tmpNum = haveToVisit.popleft()
visited.append(tmpNum)
for x in range(n):
if x != tmpNum and computers[tmpNum][x]==1 and x not in visited:
haveToVisit.append(x)
def solution(n, computers):
visited = []
answer = 0
for i in range(n):
if i not in visited:
answer+=1
BFS(i,computers,visited,n)
print(answer)
return answer
소요 시간
DFS 승
BFS 패