zoukankan      html  css  js  c++  java
  • Expm 9_1 有向图中环的判断问题

    【问题描述】

    给定一个有向图,要求使用深度优先搜索策略,判断图中是否存在环。

     1 package org.xiu68.exp.exp9;
     2 
     3 public class Exp9_1 {
     4 
     5     //用深度优先搜索判断图中是否存在环
     6     public static void main(String[] args) {
     7         // TODO Auto-generated method stub
     8         int[][] graph=new int[][]{
     9             {0,1,1,0},
    10             {0,0,0,1},
    11             {0,0,0,1},
    12             {0,0,0,0}
    13         };
    14         checkCircle(graph,4);
    15         
    16         int[][] graph1=new int[][]{
    17             {0,1,1,0},
    18             {0,0,0,1},
    19             {0,0,0,1},
    20             {1,0,0,0}
    21         };
    22         checkCircle(graph1,4);
    23     }
    24     
    25     public static void checkCircle(int[][] graph,int vexNum){
    26         //boolean[] visited=new boolean[vex.length];
    27         
    28         //每一个结点有3种状态,若为-1,则表示没访问过,若为0,则表示其后代结点正在被访问中
    29         //若为1表示结点已经访问完成
    30         int[] color=new int[vexNum];
    31         for(int i=0;i<color.length;i++)
    32             color[i]=-1;
    33         DFS(graph,0,color);
    34         
    35     }
    36     
    37     public static void DFS(int[][]    graph,int v,int[] color){
    38         if(color[v]==0){                       //存在环
    39             System.out.println("图中存在环");
    40             return;
    41         }else if(color[v]==-1){            //没搜索到该结点
    42             color[v]=0;                    //记录为正在搜索中
    43             for(int i=0;i<color.length;i++){
    44                 if(graph[v][i]==1)
    45                     DFS(graph,i,color);
    46             }
    47             color[v]=1;                    //结点v搜索完毕
    48         }
    49     }
    50     
    51 }
    View Code
  • 相关阅读:
    (转载)链表环中的入口点 编程之美 leecode 学习
    leecode single numer
    leecode 树的平衡判定 java
    Let the Balloon Rise
    Digital Roots
    大数加法,A+B
    小希的迷宫
    畅通工程
    lintcode596- Minimum Subtree- easy
    lintcode597- Subtree with Maximum Average- easy
  • 原文地址:https://www.cnblogs.com/xiu68/p/7988584.html
Copyright © 2011-2022 走看看