Count cycles of length 3 using DFS
<p>Let <code>G=(V,E)</code> be an undirected graph. How can we count cycles of length 3 exactly once using following DFS:</p>

<pre><code>DFS(G,s):
    foreach v in V do
        color[v] &lt;- white; p[v] &lt;- nil
    DFS-Visit(s)

DFS-Visit(u)
    color[u] &lt;- grey
    foreach v in Adj[u] do
        if color[v] = white then 
            p[v] = u; DFS-Visit(v)
    color[u] &lt;- black
</code></pre>

<p>There is a cycle whenever we discover a node that already has been discovered (grey). The edge to that node is called back edge. The cycle has length 3 when <code>p[p[p[v]]] = v</code>, right? So</p>

<pre><code>DFS-Visit(u)
    color[u] &lt;- grey
    foreach v in Adj[u] do
        if color[v] = grey and p[p[p[v]]] = v then
            // we got a cycle of length 3
        else if color[v] = white then 
            p[v] = u; DFS-Visit(v)
    color[u] &lt;- black
</code></pre>

<p>However how can I create a proper counter to count the number of cycles and how can I count each cycle only once?</p>