numberOfProvinces
to 0 to keep track of the number of provinces found.visited
to keep track of visited cities, initialized to false
.i
from 0 to n - 1
:
a. If city i
is not visited, increment numberOfProvinces
by 1.
b. Call the dfs
function with the current city i
to mark all cities in the current province as visited.dfs
function:
a. Mark the current city as visited.
b. Iterate over all cities j
and perform a DFS for any city directly connected to the current city and not yet visited.numberOfProvinces
as the final result.