Created
November 12, 2015 15:55
-
-
Save shashank88/131e4681587cc360ac9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Queue | |
from collections import defaultdict | |
def solution(T): | |
graph = defaultdict(list) | |
N = len(T); | |
start = -1 | |
ret = [0]*(N-1) | |
for i in xrange(N): | |
if T[i] == i: | |
start = i | |
else: | |
graph[i].append(T[i]) | |
graph[T[i]].append(i) | |
if (start == -1): | |
return ret | |
dis = 0 | |
visited = [0]*N | |
dis = [0]*N | |
q = Queue.Queue() | |
q.put(start) | |
while(q.empty() == False): | |
curr = q.get() | |
visited[curr] = 1 | |
for adjacent in graph[curr]: | |
if visited[adjacent] == 0: | |
q.put(adjacent) | |
dis[adjacent] = dis[curr]+1; | |
for element in dis: | |
if element != 0: | |
ret[element - 1] += 1 | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment