class Edge { public readonly Node First; public readonly Node Second; public Edge(Node first,Node second) { First = first; Second = second; } public bool IsIncident(Node node) { return node == First || node == Second; } public Node OtherNode (Node node) { if (First == node) return Second; else if (Second == node) return First; else throw new ArgumentException(); } } /*****************************************************/ class Graph { private Node[] nodes; public Graph(int nodesCount) { nodes = Enumerable .Range(0, nodesCount) .Select(z => new Node(z)) .ToArray(); } public Node this[int i] { get { return nodes[i]; } } public IEnumerable Nodes { get { foreach (var node in nodes) { yield return node; } } } public IEnumerable Edges { get { return Nodes.SelectMany(z => z.incidentEdges).Distinct(); } } public static Graph MakeGraph(params int[] incidentNodes) { var graph = new Graph(incidentNodes.Max() + 1); for (int i = 0; i < incidentNodes.Length - 1; i += 2) graph.Connect(incidentNodes[i], incidentNodes[i + 1]); return graph; } public void Connect(int v1,int v2) { nodes[v1].Connect(nodes[v2]); } } /*****************************************************/ class Node { private readonly List IncidentEdges = new List(); public readonly int Number; public Node(int number)//конструктор { Number = number; } public override string ToString() { return Number.ToString(); } public IEnumerable incidentNodes { get { foreach (var edge in IncidentEdges) { yield return edge.OtherNode(this); } } } public IEnumerable incidentEdges { get { foreach (var edge in incidentEdges) { yield return edge; } } } public void Connect (Node anotherNode) { var edge = new Edge(this, anotherNode); IncidentEdges.Add(edge); anotherNode.IncidentEdges.Add(edge); } } /*****************************************************/ class Program { static List BreadthSearch(Node startNode)//в ширину { var res = new List(); var queue = new Queue(); queue.Enqueue(startNode); var visited = new HashSet(); while (queue.Count!=0) { var node = queue.Dequeue(); if (visited.Contains(node)) continue; visited.Add(node); res.Add(node); foreach (var nextNode in node.incidentNodes) { queue.Enqueue(nextNode); } } return res; } static List DepthSearch(Node startNode)//в глубину { var res = new List(); var stack = new Stack(); stack.Push(startNode); var visited = new HashSet(); while (stack.Count != 0) { var node = stack.Pop(); if (visited.Contains(node)) continue; visited.Add(node); res.Add(node); foreach (var nextNode in node.incidentNodes) { stack.Push(nextNode); } } return res; } static void Main(string[] args) { var graph = Graph.MakeGraph( 0, 1, 0, 2, 1, 3, 1, 4, 2, 3, 2, 4); //graph.Connect(0, 4); foreach (var e in BreadthSearch(graph[0])) { Console.WriteLine(e.Number); } } }