【alg4-无向图】使用深度优先搜索解决双色问题

问题描述

使用深度优先搜索来判断一幅图是否能够用两种颜色将图的所有顶点着色,使得任意一条边的两个端点的颜色都不相同,这个问题等价于:这是一幅二分图吗?

代码

其中图用到了Graph:

package section4_1;

public class TwoColor {

    private boolean[] marked;
    private boolean[] color;
    private boolean isTwoColorable = true;

    public TwoColor(Graph G) {
        marked = new boolean[G.V()];
        color = new boolean[G.V()];
        for (int s = 0;s < G.V();s++) {
            if (!marked[s]) {
                dfs(G,s);
            }
        }
    }

    private void dfs(Graph G, int v) {
        marked[v] = true;
        for (int w : G.adj(v)) {
            if (!marked[w]) {
                color[w] = !color[v];
                dfs(G,w);
            } else if (color[w] == color[v]) {
                isTwoColorable = false;
            }
        }
    }

    public boolean isBipartite() {
        return isTwoColorable;
    }

    public static void main(String[] args) {
        int[][] data = {
                {0,5},
                {0,1},
                {0,2},
                {0,6},
                {5,3},
                {3,1},
                {4,5},
                {4,6},
                {6,7},
                {7,8},
                {8,10},
                {9,10},
                {9,11},
                {11,12},
                {12,10}
        };
        int vn = 13;
        int e = 15;
        Graph graph = new Graph(vn,e,data);
        TwoColor test = new TwoColor(graph);
        System.out.println(test.isBipartite());

        int[][] data2 = {
                {0,1},
                {0,2},
                {0,3},
                {2,3}
        };
        int vn2 = 4;
        int e2 = 4;
        Graph graph2 = new Graph(vn2,e2,data2);
        TwoColor test2 = new TwoColor(graph2);
        System.out.println(test2.isBipartite());
    }
}

在这里插入图片描述

你可能感兴趣的:(算法,算法)