zoukankan      html  css  js  c++  java
  • 785. 判断二分图

      判断二分图,使用染色法

     方法一:BFS

    public boolean isBipartite(int[][] graph) {
            int n = graph.length;
            int[] color = new int[n];  // 染色数组 0表示为染色, 1 -1为不同色
            for(int i = 0; i < n; i++) { // 每个位置开始,进行BFS染色
                if(color[i] != 0) continue;
                color[i] = 1;
                Deque<Integer> queue = new LinkedList<>();
                queue.add(i);
                while(!queue.isEmpty()) {
                    int num = queue.poll();
                    for(int j = 0; j < graph[num].length; j++) {
                        if(color[graph[num][j]] == color[num]) return false;
                        else if (color[graph[num][j]] == 0) {
                            color[graph[num][j]] = -color[num];
                            queue.add(graph[num][j]);
                        }
                    }
                }
            }
            return true;
        }

    方法二:DFS

        public boolean isBipartite(int[][] graph) {
            int n = graph.length;
            int[] color = new int[n];
            for(int i = 0; i < n; i++) {   // 每个位置进行DFS染色
                if(color[i] != 0) continue;
                if(!dfs(graph,i,color,1)) return false;
            }
            return true;
        }                                 // num为当前点 color为染色数组 pre为上一个颜色
        public boolean dfs(int[][] graph, int num, int[] color, int pre) {
            if(color[num] == pre) return false;
            if(color[num] == -pre) return true;
            color[num] = -pre;
            for(int i = 0; i < graph[num].length; i++) {
                if(!dfs(graph,graph[num][i],color,-pre)) return false;
            }
            return true;
        }
  • 相关阅读:
    大型网站优化-memcache技术
    MySQL常见注意事项及优化
    网站优化—mysql explain执行计划
    网站优化—MySQL优化
    网站优化—页面静态化技术
    防盗链案例
    伪静态的实现
    (19) PHP 随笔---LAMP 系统常用命令
    (17) PHP 随笔---LAMP vi编辑器
    (18) PHP 随笔---LAMP 权限操作
  • 原文地址:https://www.cnblogs.com/yonezu/p/13322727.html
Copyright © 2011-2022 走看看