第一步 建立有向图

第二步 判断是否有环

Detect Cycle in a Directed Graph - GeeksforGeeks

// A C# Program to detect cycle in a graph
using System;
using System.Collections.Generic;

public class Graph {
	
	private readonly int V;
	private readonly List<List<int>> adj;

	public Graph(int V)
	{
		this.V = V;
		adj = new List<List<int>>(V);
		
		for (int i = 0; i < V; i++)
			adj.Add(new List<int>());
	}

	private bool isCyclicUtil(int i, bool[] visited, bool[] recStack)
	{
			// Mark the current node as visited and part of recursion stack
			if (recStack[i]) return true;
			if (visited[i]) return false;
			visited[i] = true;
			recStack[i] = true;
			List<int> children = adj[i];
		
			foreach (int c in children)
				if (isCyclicUtil(c, visited, recStack)) return true;
			recStack[i] = false;
			return false;
	}

	// Returns true if the graph contains a cycle, else false.
	private bool isCyclic()
	{
		bool[] visited = new bool[V];
		bool[] recStack = new bool[V];
		
		for (int i = 0; i < V; i++)
			if (isCyclicUtil(i, visited, recStack))
				return true;
		return false;
	}

第三步 解题

1. 有向无环图最长路

①无权

②加权

2. 有向有环图最长路

①没有-r参数