InferenceAI

Enter at least two characters to search.

Start free

Connected Provinces

mediumGraphs25 min25 XP

connected[i][j] is 1 if city i and city j are directly connected. A province is a group of directly or indirectly connected cities. Return the number of provinces.

Examples

EXAMPLE WALKTHROUGHtwo provinces

A guided view of the published example, not a trace of your code.

INPUT[[[1,1,0],[1,1,0],[0,0,1]]]
TASKconnected_provinces()
EXPECTED OUTPUT2

Start with the input values shown in this example.

Example 1 of 3

Input: connected = [[1,1,0],[1,1,0],[0,0,1]]

Output: 2

Explanation: two provinces

Input: connected = [[1,0,0],[0,1,0],[0,0,1]]

Output: 3

Explanation: all separate

Input: connected = [[1]]

Output: 1

Explanation: single city

Hint 1

Run DFS from each unvisited city, or use union-find.

Topics

DSAGraphsPython