/// <summary> /// Colors graph vertices greedily processing them in order of <paramref name="verticesOrdered"/>. /// </summary> /// <param name="graph">Graph to be colored.</param> /// <param name="verticesOrdered">Ordering of graph vertices to use in algorithm.</param> /// <param name="adjacency"><paramref name="graph"/> adjacency to save calculations /// when doing multiple colorings.</param> /// <returns>Vertex coloring of provided graph.</returns> public static GraphColoring ColorGreedilyWithVertexOrder(this Graph graph, IEnumerable <Vertex> verticesOrdered, VertexAdjacency adjacency) { var maxDegree = adjacency.AdjacentVertices.Max(p => p.Value.Count); var colors = Enumerable.Range(1, maxDegree + 2); var coloring = new MutableGraphColoring(graph); foreach (var vertex in verticesOrdered) { var adjacentVertices = adjacency.AdjacentVertices[vertex]; var usedColors = adjacentVertices.Select(v => coloring[v]).Where(c => c != null).Select(c => c.Value); var color = colors.Except(usedColors).First(); coloring[vertex] = color; } return(coloring.ToImmutable()); }
/// <summary> /// Colors graph using G.I.S (Greedy Independent Sets) algorithm. See remarks in <see cref="ColorGreedyIndependentSets(Graph)"/>. /// </summary> /// <param name="graph">Graph to be colored.</param> /// <param name="adjacency"><paramref name="graph"/> adjacency to save calculations /// when doing multiple colorings.</param> /// <returns>Vertex coloring of provided graph.</returns> public static GraphColoring ColorGreedyIndependentSets(this Graph graph, VertexAdjacency adjacency) { var maxDegree = adjacency.AdjacentVertices.Max(p => p.Value.Count); var color = 1; var coloring = new MutableGraphColoring(graph); while (coloring.VertexColors.Count < graph.Vertices.Count) { var induced = adjacency.InducedSubgraphByRemovingVertices(coloring.VertexColors.Keys); var inducedAdjacency = induced.Adjacency(); while (induced.Subgraph.Vertices.Count > 0) { var vertex = induced.Subgraph.MinDegreeVertex(inducedAdjacency.VertexDegrees()); coloring[vertex] = color; induced = inducedAdjacency.InducedSubgraphByRemovingVertices(inducedAdjacency.AdjacentVertices[vertex].Add(vertex)); inducedAdjacency = induced.Adjacency(); } color++; } return(coloring.ToImmutable()); }