Created
October 5, 2022 05:18
-
-
Save powerwlsl/d406d1ee6776744c357261c4fc882bdb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# @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