547. Number of Provinces

use BFS

time: O(n^2), matrix size

space: O(n), use queue & visited array

don't use visited array, just set isConnected[][] = 2 as visited, but space is still O(n)

another way is to use union find

union find

time: O(n^2), matrix size

space: O(n), union find map size

Last updated

Was this helpful?