算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 省份数量,我们先来看题面:
https://leetcode-cn.com/problems/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.
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。
返回矩阵中 省份 的数量。
示例
解题
https://www.jianshu.com/p/ad8f5413a7ea
运用BFS的方法,先找到一条路径的所有连接城市,然后+1,接着找下一条。
首先审题,参数矩阵是一个方阵且是对称矩阵,对角线都是1代表自身相连。所以我们从0开始遍历,代表第一个城市,先判断是否访问,未被访问就入队,然后寻找所有直接和间接相连接的城市,即矩阵值为1且未访问的城市,然后入队。
class Solution {
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
int res = 0;
// 记录已访问城市
List<Integer> visited = new ArrayList<>();
// 记录路径
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
// 未访问城市入队
if (!visited.contains(i)) {
queue.offer(i);
while (!queue.isEmpty()) {
int cur = queue.poll();
// 当前城市已访问
visited.add(cur);
// 寻找连接城市
for (int j = 0; j < n; j++) {
if (isConnected[cur][j] == 1 && !visited.contains(j)) {
// 连接城市入队
queue.offer(j);
}
}
}
res++;
}
}
return res;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: