( graph: Graph<N, E, "undirected"> | MutableGraph<N, E, "undirected"> )
| 2032 | * @category algorithms |
| 2033 | */ |
| 2034 | export const isBipartite = <N, E>( |
| 2035 | graph: Graph<N, E, "undirected"> | MutableGraph<N, E, "undirected"> |
| 2036 | ): boolean => { |
| 2037 | const coloring = new Map<NodeIndex, 0 | 1>() |
| 2038 | const discovered = new Set<NodeIndex>() |
| 2039 | let isBipartiteGraph = true |
| 2040 | |
| 2041 | // Get all nodes to handle disconnected components |
| 2042 | for (const startNode of graph.nodes.keys()) { |
| 2043 | if (!discovered.has(startNode)) { |
| 2044 | // Start BFS coloring from this component |
| 2045 | const queue: Array<NodeIndex> = [startNode] |
| 2046 | coloring.set(startNode, 0) // Color start node with 0 |
| 2047 | discovered.add(startNode) |
| 2048 | |
| 2049 | while (queue.length > 0 && isBipartiteGraph) { |
| 2050 | const current = queue.shift()! |
| 2051 | const currentColor = coloring.get(current)! |
| 2052 | const neighborColor: 0 | 1 = currentColor === 0 ? 1 : 0 |
| 2053 | |
| 2054 | // Get all neighbors for undirected graph |
| 2055 | const nodeNeighbors = getUndirectedNeighbors(graph, current) |
| 2056 | for (const neighbor of nodeNeighbors) { |
| 2057 | if (!discovered.has(neighbor)) { |
| 2058 | // Color unvisited neighbor with opposite color |
| 2059 | coloring.set(neighbor, neighborColor) |
| 2060 | discovered.add(neighbor) |
| 2061 | queue.push(neighbor) |
| 2062 | } else { |
| 2063 | // Check if neighbor has the same color (conflict) |
| 2064 | if (coloring.get(neighbor) === currentColor) { |
| 2065 | isBipartiteGraph = false |
| 2066 | break |
| 2067 | } |
| 2068 | } |
| 2069 | } |
| 2070 | } |
| 2071 | |
| 2072 | // Early exit if not bipartite |
| 2073 | if (!isBipartiteGraph) { |
| 2074 | break |
| 2075 | } |
| 2076 | } |
| 2077 | } |
| 2078 | |
| 2079 | return isBipartiteGraph |
| 2080 | } |
| 2081 | |
| 2082 | /** |
| 2083 | * Get neighbors for undirected graphs by checking both adjacency and reverse adjacency. |
nothing calls this directly
no test coverage detected