有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
示例 1:
输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]]
输出:2
示例 2:
输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]]
输出:3
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-provinces
class Solution {
// DFS
// Time: O(n^2) The complete matrix of size n^2 is traversed
// Space: O(n), visited array of size n is traversed.
// This wants to find # of friend circles,
// which 1 friend circle = students with 1 that are connected to each others in matrix
// In the future I can try BFS to solve this question!
// 思路:好友关系可以看成是一个无向图,例如第 0 个人与第 1 个人是好友,那么 M[0][1] 和 M[1][0] 的值都为 1,依次遍历这些同学,即遍历到某位同学,就给他打一个标记。使用一个hasVisited数组, 依次判断每个节点,如果其未访问,朋友圈数加1并对该节点进行dfs搜索标记所有访问到的节点。
// Note: The key of this problem is: Create a boolean array to determine & count the numFriends.
public int findCircleNum(int[][] M) {
boolean[] visited = new boolean[M[0].length];
int numFriCir = 0;
//遍历N个人,从0--->N-1
for (int i = 0; i < M[0].length; i++) {
//某同学还没有被遍历过
if (!visited[i]) {
visited[i] = true;
dfs(i, M, visited);
numFriCir++;
}
}
return numFriCir;
}
public void dfs (int col, int[][] M, boolean[] visited) {
for (int i = 0; i < M[0].length; i++) {
//M[i][n]其实就等于M[n][i],当前第i同学还没有被访问(并且i!=n)
if(M[i][col] == 1 && !visited[i]) {
//设置已访问标记
visited[i] = true;
// Keep iterate & update the boolean array as long as the nearby cell is friends (1)
dfs(i, M, visited);
}
}
}
}
// 笔记
// # doing this problem: 1.
// Can not Complete this question, I use a same coding as num of island
// public int findCircleNum(int[][] M) {
// int[] visited = new int[M.length];
// int count = 0;
// for (int i = 0; i < M.length; i++) {
// if (visited[i] == 0) {
// dfs(M, visited, i);
// count++;
// }
// }
// return count;
// }
// // call dfs function recursively
// public void dfs(int[][] M, int[] visited, int i) {
// for (int j = 0; j < M.length; j++) {
// if (M[i][j] == 1 && visited[j] == 0) {
// visited[j] = 1;
// dfs(M, visited, j);
// }
// }
// }```