尽可能使用DSF查找包含3个以上顶点的循环

时间:2019-04-17 07:21:43

标签: graph-theory implementation depth-first-search

我正在实现一种最佳解决方案算法,需要找到一个包含3个以上顶点的循环,因为不允许对角线连接(仅上/下,左/右)。如果有任何建议或可以为我指明资源的方向,我将不胜感激。

我已经使用邻接矩阵实现了链表方法。我基于this 但是它只在第一个循环中停止,该循环仅包含3个顶点。

我当前的代码使用自定义对象集合,因此与此有所不同。

// A Java Program to detect cycle in a graph 
class Graph { 
    private final int V; 
    private final List<List<Integer>> adj; 

    public Graph(int V)  
    { 
        this.V = V; 
        adj = new ArrayList<>(V); 

        for (int i = 0; i < V; i++) 
            adj.add(new LinkedList<>()); 

    }     

    // This function is a variation of DFSUytil() in  

    // https://www.geeksforgeeks.org/archives/18212 

    private boolean isCyclicUtil(int i, boolean[] visited, 

                                      boolean[] recStack)  

    { 

        // Mark the current node as visited and 
        // part of recursion stack 
        if (recStack[i]) 

            return true; 

        if (visited[i]) 

            return false; 

        visited[i] = true;   

        recStack[i] = true; 

        List<Integer> children = adj.get(i);          

        for (Integer c: children) 
            if (isCyclicUtil(c, visited, recStack)) 
                return true;                

        recStack[i] = false; 

        return false; 

    } 

    private void addEdge(int source, int dest) { 

        adj.get(source).add(dest); 
    } 

    // Returns true if the graph contains a  
    // cycle, else false. 
    // This function is a variation of DFS() in  
    // https://www.geeksforgeeks.org/archives/18212 
    private boolean isCyclic()  
    { 
        // Mark all the vertices as not visited and 
        // not part of recursion stack 

        boolean[] visited = new boolean[V]; 

        boolean[] recStack = new boolean[V]; 

        // Call the recursive helper function to 

        // detect cycle in different DFS trees 

        for (int i = 0; i < V; i++) 

            if (isCyclicUtil(i, visited, recStack)) 

                return true; 
        return false; 

    } 
    public static void main(String[] args) 

    { 
        Graph graph = new Graph(5); 
        graph.addEdge(0, 1); 
        graph.addEdge(0, 2); 
        graph.addEdge(1, 2); 
        graph.addEdge(2, 0); 
        graph.addEdge(2, 3); 
        graph.addEdge(3, 3); 

        graph.isCyclic();

    } 
} 

我无法发布确切的代码,因为我可能会被标记为gi窃

An example of a cycle I would like to find is:
00000
01010
01010
Where the 4 edged cycle is represent by 1s
At the moment I get a result where a cycle
00000
00000
01110
and this is not what I need.

0 个答案:

没有答案