Number of Provinces
Given an adjacency matrix of cities, count the number of connected provinces (groups of directly/indirectly connected cities).
Open on LeetCode ↗Intuition
The trap is reading isConnected as an edge list. It is an adjacency matrix -- isConnected[i][j] == 1 means an edge, and the matrix is symmetric, so a naive loop over every pair visits each edge twice. What actually answers the question is the number of connected components: run DFS or Union-Find and count how many times a fresh traversal had to start because the city was still unvisited. Every fresh start is exactly one province, so the traversal both explores the graph and counts the answer in the same pass.
Approach
Read it as a matrix, not edges
isConnected[i][j] == 1 tells you cities i and j are directly connected. Because the matrix is symmetric, scanning it as if it were an edge list double counts every connection -- treat it purely as an adjacency structure to query, not a list to iterate pairwise.
DFS from every unvisited city
Loop i from 0 to n-1. If city i has not been visited, that means no earlier DFS reached it, so it belongs to a brand new province: increment the counter and flood-fill from i, marking every reachable city visited.
The counter and the traversal are the same pass
There is no separate 'count components' step. Each time the outer loop finds an unvisited city, that single event is one more province, because everything reachable from it gets marked before the loop moves on.
Solution & live demo
Edge cases
Every city starts its own DFS, so provinces == n.
First DFS visits every city; provinces == 1.
One DFS call, provinces == 1.
Self-loops are ignored by skipping j == i during the scan; they never affect connectivity.