Skip to content

Instantly share code, notes, and snippets.

@tekihei2317
Created November 3, 2020 02:54
Show Gist options
  • Select an option

  • Save tekihei2317/8e238cb72852db043c56847c3c40bec7 to your computer and use it in GitHub Desktop.

Select an option

Save tekihei2317/8e238cb72852db043c56847c3c40bec7 to your computer and use it in GitHub Desktop.
Rubyで深さ優先探索
def solve
n, m, g = gets.split(' ').map(&:to_i)
graph = Array.new(n) { Array.new }
m.times do
a, b = gets.split(' ').map(&:to_i)
graph[b - 1] << a - 1
end
visited = Array.new(n, false)
dfs = ->(crt) do
visited[crt] = true
graph[crt].each do |nxt|
dfs.call(nxt) if !visited[nxt]
end
end
dfs.call(g - 1)
puts visited.all?(true) ? 'OK' : 'NG'
end
solve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment