diff --git "a/2101040022/chapter_8/\345\210\244\346\226\255\344\272\214\345\210\206\345\233\276.cpp" "b/2101040022/chapter_8/\345\210\244\346\226\255\344\272\214\345\210\206\345\233\276.cpp" new file mode 100644 index 0000000000000000000000000000000000000000..b0727627b858ef06a525aa8194e69bc267b6b9bb --- /dev/null +++ "b/2101040022/chapter_8/\345\210\244\346\226\255\344\272\214\345\210\206\345\233\276.cpp" @@ -0,0 +1,30 @@ +bool dfs(int node, int c, int* color, int** graph, int* graphColSize) { + color[node] = c; + int cNei = (c == 1 ? 2 : 1); + for (int i = 0; i < graphColSize[node]; ++i) { + int neighbor = graph[node][i]; + if (color[neighbor] == 0) { + if (!dfs(neighbor, cNei, color, graph, graphColSize)) { + return false; + } + } else if (color[neighbor] != cNei) { + return false; + } + } + return true; +} + +bool isBipartite(int** graph, int graphSize, int* graphColSize) { + int* color = (int*)malloc(sizeof(int) * graphSize); + memset(color, 0, sizeof(int) * graphSize); + for (int i = 0; i < graphSize; ++i) { + if (color[i] == 0) { + if (!dfs(i, 1, color, graph, graphColSize)) { + free(color); + return false; + } + } + } + free(color); + return true; +} \ No newline at end of file