Skip to content

Instantly share code, notes, and snippets.

@powerwlsl
Created October 5, 2022 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save powerwlsl/d406d1ee6776744c357261c4fc882bdb to your computer and use it in GitHub Desktop.
Save powerwlsl/d406d1ee6776744c357261c4fc882bdb to your computer and use it in GitHub Desktop.
# @param {Integer[][]} is_connected
# @return {Integer}
def find_circle_num(is_connected)
visited = Array.new(is_connected.length, 0)
count = 0
for i in 0...is_connected.length
if visited[i] == 0 && visited.uniq != [1]
dfs(i, is_connected, visited, [i])
count += 1
end
end
count
end
def dfs(i, is_connected, visited, stack = [])
return if visited.uniq == 1
return if i.nil?
for j in 0...is_connected.length
stack.push(j) if is_connected[i][j] == 1 && visited[j] == 0
end
while stack.length > 0
current = stack.shift
visited[current] = 1
dfs(stack[0], is_connected, visited, stack)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment