LeetCode Daily Question 17
Apr 6th 2022
4 月 6 日 每日一题
题目:547. Number of Provinces
There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
1 | Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] |
思路
遍历所有 vertex,如果当前 vertex 为 unvisited,num++,并且使用 dfs 遍历该所有和该节点在一个 province 的节点,并把他们标记为 visited。dfs 结束后回到原函数继续对剩余 vertex 进行遍历。
代码
1 | class Solution { |