public static Boolean IsBiPartite(Graph graph) { Boolean[] visited = new Boolean[graph.VerticesCount]; Boolean[] color = new Boolean[graph.VerticesCount]; Boolean isBiPartite = true; for (int i = 0; i < graph.VerticesCount; i++) { if (!visited[i]) { if (!IsBiPartite(i)) { break; } } } return(isBiPartite); Boolean IsBiPartite(Int32 vertice) { visited[vertice] = true; using (var adjacents = graph.GetAdjacentVertices(vertice).GetEnumerator()) { while (isBiPartite && adjacents.MoveNext()) { // If one of my adjacents was visited and his color is equal to mine // it means I'm pointing to a vertice that is on the same side as me. // // 0 ------> 2 // ^ // | // | // 0 ------> 1 if (!visited[adjacents.Current]) { color[adjacents.Current] = !color[vertice]; IsBiPartite(adjacents.Current); } else if (color[adjacents.Current] == color[vertice]) { isBiPartite = false; } } } return(isBiPartite); } }
private void DFS(Graph graph, Int32 vertice) { this._visited[vertice] = true; this._ids[vertice] = this.Count; foreach (Int32 adjacentVertice in graph.GetAdjacentVertices(vertice)) { if (!this._visited[adjacentVertice]) { this.DFS(graph, adjacentVertice); } } }
public static Boolean HasCycle(Graph graph) { Boolean[] visited = new Boolean[graph.VerticesCount]; Boolean hasCycle = false; for (int i = 0; i < graph.VerticesCount; i++) { if (!visited[i]) { if (HasCycle(i, i)) { break; } } } return(hasCycle); Boolean HasCycle(Int32 vertice, Int32 parentVertice) { visited[vertice] = true; using (var adjacents = graph.GetAdjacentVertices(vertice).GetEnumerator()) { while (!hasCycle && adjacents.MoveNext()) { if (adjacents.Current == vertice) // Self-loop: my adjacent is me. { hasCycle = true; } else if (!visited[adjacents.Current]) { HasCycle(adjacents.Current, vertice); } else if (adjacents.Current != parentVertice) // Back-edge: if it's visited and not my parent so it looped to a vertice. { hasCycle = true; } } } return(hasCycle); } }