Number of Triangles in a Directed and Undirected Graph

Pattern: Representations

easy

With an adjacency matrix, check every ordered triple a, b, c of distinct vertices for edges a → b, b → c, c → a. A directed triangle is found 3 times (its rotations) and an undirected one 6 times (rotations in both directions), so divide accordingly.

The problem

Given an adjacency matrix and whether the graph is directed, return the number of triangles: three vertices joined in a cycle (a → b → c → a when directed).

Think first

  • How many ordered triples does one triangle produce?
  • Is that different for directed graphs?
  • How do you avoid counting a vertex twice?

Hints

    Brute force, and why it fails

    The same triple loop is the brute force; matrix multiplication (trace of A³) is faster in theory.

    The key insight

    Counting ordered cycles and dividing by the number of times each triangle repeats avoids any special handling.

    Dry run

    Undirected matrix on 4 vertices with edges 0-1, 0-2, 1-2, 1-3, 2-3. Triangles: {0, 1, 2} and {1, 2, 3}.

    Step 1 of 3

    The plan

    for a, b, c distinct: if m[a][b] and m[b][c] and m[c][a]: count += 1
    return count / 3 if directed else count / 6
    

    Complexity

    Time
    O(V³)
    Space
    O(1)

    Three nested loops over the vertices.

    Edge cases

    • No edges: 0.
    • A complete graph on 4 vertices: 4 triangles.
    • Directed edges that form a path, not a cycle: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int countTriangles(int[][] m, boolean directed) {
            int n = m.length, count = 0;
            for (int a = 0; a < n; a++)             // every ordered triple a -> b -> c -> a
                for (int b = 0; b < n; b++)
                    for (int c = 0; c < n; c++)
                        if (a != b && b != c && a != c && m[a][b] == 1 && m[b][c] == 1 && m[c][a] == 1) count++;
            return directed ? count / 3 : count / 6;   // each triangle is counted 3 times directed, 6 undirected
        }
    }

    C++

    class Solution {
    public:
        int countTriangles(vector<vector<int>>& m, bool directed) {
            int n = static_cast<int>(m.size()), count = 0;
            for (int a = 0; a < n; a++)             // every ordered triple a -> b -> c -> a
                for (int b = 0; b < n; b++)
                    for (int c = 0; c < n; c++)
                        if (a != b && b != c && a != c && m[a][b] == 1 && m[b][c] == 1 && m[c][a] == 1) count++;
            return directed ? count / 3 : count / 6;   // each triangle is counted 3 times directed, 6 undirected
        }
    };

    Python

    class Solution:
        def countTriangles(self, m: list[list[int]], directed: bool) -> int:
            n, count = len(m), 0
            for a in range(n):                      # every ordered triple a -> b -> c -> a
                for b in range(n):
                    for c in range(n):
                        if a != b != c != a and m[a][b] and m[b][c] and m[c][a]:
                            count += 1
            return count // 3 if directed else count // 6   # each triangle is counted 3 times directed, 6 undirected

    Common mistakes

    • Dividing by 6 for directed graphs.
    • Counting a triple with repeated vertices.

    Similar problems