547. Friend Circles

刺骨的言语ヽ痛彻心扉 2023-07-01 10:57 96阅读 0赞

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:

  1. Input:
  2. [[1,1,0],
  3. [1,1,0],
  4. [0,0,1]]
  5. Output: 2
  6. Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
  7. The 2nd student himself is in a friend circle. So return 2.

Example 2:

  1. Input:
  2. [[1,1,0],
  3. [1,1,1],
  4. [0,1,1]]
  5. Output: 1
  6. Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
  7. so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.

Note:

  1. N is in range [1,200].
  2. M[i][i] = 1 for all students.
  3. If M[i][j] = 1, then M[j][i] = 1.

解法:遍历+ 深度搜索。

  1. class Solution {
  2. public:
  3. void DFS(int i, int j, vector<vector<int>>& grid)
  4. {
  5. if (grid[i][j] == 1)
  6. {
  7. grid[i][j] = 0;
  8. for (int k = 0; k < grid.size(); k++)
  9. {
  10. if (grid[j][k])
  11. {
  12. DFS(j, k, grid);
  13. }
  14. }
  15. }
  16. }
  17. int findCircleNum(vector<vector<int>>& grid) {
  18. if (grid.size() == 0 || grid[0].size() == 0)
  19. {
  20. return 0;
  21. }
  22. int count = 0;
  23. for (int i = 0; i < grid.size(); i++)
  24. {
  25. for (int j = 0; j < grid[0].size(); j++)
  26. {
  27. if (grid[i][j] == 1)
  28. {
  29. DFS(i, j, grid);
  30. count++;
  31. }
  32. }
  33. }
  34. return count;
  35. }
  36. };

发表评论

表情:
评论列表 (有 0 条评论,96人围观)

还没有评论,来说两句吧...

相关阅读

    相关 547. 省份数量

    547. 省份数量 有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接

    相关 547. 省份数量

    题目描述: > 有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。