[LeetCode] 547. Friend Circles Java
題目:
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:
Input: [[1,1,0],[1,1,0],[0,0,1]] Output: 2 Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input: [[1,1,0],[1,1,1],[0,1,1]] Output: 1 Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
題意及分析:求朋友圈個(gè)數(shù),若M[i][j]==1,則i,j為朋友,朋友有傳遞性,直接朋友或者間接朋友組成一個(gè)朋友圈。按照?qǐng)D論的方式來(lái)講給出一個(gè)圖的鄰接矩陣,求不相鄰的子圖個(gè)數(shù)。我第一次用了寬度遍歷,對(duì)于其中一個(gè)點(diǎn)M[i][j],若該點(diǎn)未被遍歷過,則把該點(diǎn)標(biāo)記為已遍歷,然后遍歷第i,j行和i,j列(即寬度遍歷),找到為1的且未被遍歷過的點(diǎn),重復(fù)操作。但是此方法時(shí)間復(fù)雜度較高,排名基本上在最后面了。。。 另一種是聲明一個(gè)visited,用于記錄遍歷過的結(jié)點(diǎn)。每次dfs找到一個(gè)原矩陣為1的位置(除了對(duì)角線),就把這個(gè)位置的列數(shù)變成行數(shù)再dfs,如果是在同一個(gè)圈里,最終會(huì)繞回已經(jīng)遍歷過的行,visited為true,return 0;如果不是同一個(gè)圈,則增加1。(mat[i][j]==1這個(gè)判斷相當(dāng)于i的鄰接點(diǎn),深度優(yōu)先遍歷)
代碼:
?代碼:
public class Solution {public int findCircleNum(int[][] M) {if (M == null && M.length == 0)return 0;int n = M.length;boolean[] visited = new boolean[n];int count = 0;//如果dfs大于0,說(shuō)明有未遍歷的結(jié)點(diǎn)//只需要遍歷所有結(jié)點(diǎn)for (int i = 0; i < n; i++)if (dfs(M, i, visited) > 0)count++;return count;}private int dfs(int[][] mat, int i, boolean[] visited) {if (visited[i])return 0;visited[i] = true;int count = 1;for (int j = 0; j < visited.length; j++)if (i != j && mat[i][j] == 1)count += dfs(mat, j, visited);return count;} }?
轉(zhuǎn)載于:https://www.cnblogs.com/271934Liao/p/7245550.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode] 547. Friend Circles Java的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 直播视频网站源码,静态时钟
- 下一篇: java collection api_