Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS.

Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS.
static int provinces(int[][] m) {
    int n = m.length, c = 0;
    boolean[] seen = new boolean[n];
    for (int i = 0; i < n; i++)
        if (!seen[i]) { c++; dfs(m, seen, i); }
    return c;
}
static void dfs(int[][] m, boolean[] seen, int u) {
    seen[u] = true;
    for (int v = 0; v < m.length; v++) if (m[u][v] == 1 && !seen[v]) dfs(m, seen, v);
}
// provinces({{1,1,0,0},{1,1,0,0},{0,0,1,0},{0,0,0,1}})
What does the call return?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 1

Correct answer: B. 3

Cities 0 and 1 are connected; 2 and 3 are isolated (only self-loops on the diagonal). Each DFS launched from an unseen city marks a whole province: 3. With an adjacency matrix this is O(n²).

More Coding Interview Problems questions

Exams that ask this topic