简体   繁体   中英

Python - How do I do check for a Directed Acyclic Graph without using stack and class?

so what I'm trying to do is to create a function to check if a graph is a directed acyclic graph (DAG) or not.

So I'm given the vertexes and adjacency list only to start off my code.

The catch is that I am not allowed to use Stacks (from Linear Data Structures), classes, and also not allowed to use other Python libraries/ packages, just pure python. (so no networkx/ matplotlib allowed)

I understand that a directed acyclic graph has at least 1 topological sorting, but I'm not sure how to code it out. Now, my current idea is to use a recursion DFS and a topological sort, but I'm not sure (again) if these are meant to be combined together or if I need seperate functions for this.

Maybe this works:

For nodeY in all nodes:

Use a Breadth-first search algorithm starting with the current nodeY. ( In Python )

Create a set() and add nodeY.

At each nodeX you visit check if the current nodeX is already in the set.

If yes then the graph is cyclic, algo finished. If not then add the current nodeX to the set.

If you visited all reachable nodes via Breadth-first search then proceed with the next node as nodeY as a starting point for the algorithm.

If there is not next nodeY finish the algorithm. -> Acyclic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM