[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:

  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.

题意及分析:求朋友圈个数,若M[i][j]==1,则i,j为朋友,朋友有传递性,直接朋友或者间接朋友组成一个朋友圈。按照图论的方式来讲给出一个图的邻接矩阵,求不相邻的子图个数。我第一次用了宽度遍历,对于其中一个点M[i][j],若该点未被遍历过,则把该点标记为已遍历,然后遍历第i,j行和i,j列(即宽度遍历),找到为1的且未被遍历过的点,重复操作。但是此方法时间复杂度较高,排名基本上在最后面了。。。 另一种是声明一个visited,用于记录遍历过的结点。每次dfs找到一个原矩阵为1的位置(除了对角线),就把这个位置的列数变成行数再dfs,如果是在同一个圈里,最终会绕回已经遍历过的行,visited为true,return 0;如果不是同一个圈,则增加1。(mat[i][j]==1这个判断相当于i的邻接点,深度优先遍历
代码:

public class Solution {
    public int findCircleNum(int[][] M) {
        int res = 0;
        int row= M.length;
        if(row==0) return 0;
        for(int i=0;i<row;i++){         //只遍历矩阵下半部分
            for(int j=0;j<=i;j++){
                if(M[i][j]==1){     //未被遍历过的值为1的点
                    res++;
                    boolean[] rowVisited = new boolean[row];        //记录已经遍历过的行
                    boolean[] colVisited = new boolean[row];        //记录已经遍历过的列
                    Integer[] index = {i,j};
                    Queue<Integer[]> queue = new LinkedList<>();
                    queue.add(index);  //查找该个点组成的朋友圈,能和该点组成朋友圈的点满足在i,j行或者i,j列
                    while(!queue.isEmpty()){

                        Integer[] val = queue.poll();
                        int x =val[0],y=val[1];
                        if(M[x][y]==1){     //防止重复
                            M[x][y] = 2;        //将遍历过的点置为2
                            if(!rowVisited[x]){
                                for(int m=0;m<=x;m++){      //x行
                                    Integer[]  addIndex = {x,m};
                                    if(M[x][m]==1 && !queue.contains(addIndex)) queue.add(addIndex);
                                }
                                rowVisited[x]=true;
                            }
                            if(!rowVisited[y]){
                                for(int n=0;n<=y;n++){         //第y行
                                    Integer[]  addIndex = {y,n};
                                    if(M[y][n]==1) queue.add(addIndex);
                                }
                                rowVisited[y]=true;
                            }

                            if(!colVisited[x]){
                                for(int m=x;m<row;m++){     //第x列
                                    Integer[]  addIndex = {m,x};
                                    if(M[m][x]==1&& !queue.contains(addIndex)) queue.add(addIndex);
                                }
                                colVisited[x]=true;
                            }

                            if(!colVisited[y]){
                                for(int m=y;m<row;m++){     //第y列
                                    Integer[]  addIndex = {m,y};
                                    if(M[m][y]==1&& !queue.contains(addIndex)) queue.add(addIndex);
                                }
                                colVisited[y]=true;
                            }
                        }

                    }
                }
            }
        }
        return res;
    }
}

 代码:

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,说明有未遍历的结点
        //只需要遍历所有结点
        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;
    }
}

 

转载于:https://www.cnblogs.com/271934Liao/p/7245550.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Java中的排序功能来实现。可以使用Arrays.sort()函数,将列表中的元素按照字母顺序排序,或者使用Collections.sort()函数,将列表中的元素按用户指定的排序规则排序。 ### 回答2: 为了实现LeetCode 2561题(Rearranging Fruits)的要求,需要使用Java编程语言。主要思路是遍历给定的水果数组,同时用一个哈希表来记录每个水果出现的次数。然后根据题目要求,重新排列水果使得相同类型的水果尽可能接近,并且按照出现次数的非递增顺序排序。 具体实现步骤如下: 1. 创建一个HashMap来存储每个水果的出现次数。遍历给定的水果数组,如果该水果已经存在于HashMap中,则将其出现次数加1;否则,将该水果添加到HashMap,并将其出现次数初始化为1。 2. 创建一个ArrayList来存储已经排列好的水果。通过HashMap的entrySet方法获取到每种水果和它的出现次数,然后将这些entry按照出现次数的非递增顺序进行排序。 3. 遍历排序好的entry集合,根据每个水果的出现次数,在ArrayList中连续添加相应数量的水果。 4. 返回排列好的水果数组。 以下是Java代码的示例实现: ```java import java.util.*; class Solution { public String[] rearrange(String[] fruits) { HashMap<String, Integer> fruitCountMap = new HashMap<>(); // 统计每个水果的出现次数 for (String fruit : fruits) { if (fruitCountMap.containsKey(fruit)) { fruitCountMap.put(fruit, fruitCountMap.get(fruit) + 1); } else { fruitCountMap.put(fruit, 1); } } ArrayList<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(fruitCountMap.entrySet()); // 根据出现次数进行非递增排序 Collections.sort(sortedEntries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { return entry2.getValue().compareTo(entry1.getValue()); } }); ArrayList<String> rearrangedFruits = new ArrayList<>(); // 根据出现次数连续添加水果 for (Map.Entry<String, Integer> entry : sortedEntries) { String fruit = entry.getKey(); int count = entry.getValue(); for (int i = 0; i < count; i++) { rearrangedFruits.add(fruit); } } return rearrangedFruits.toArray(new String[0]); } } ``` 使用以上代码,可以对给定的水果数组进行重新排列,使得相同类型的水果尽可能接近,并且按照出现次数的非递增顺序进行排序。返回的结果就是排列好的水果数组。 ### 回答3: 题目要求将一个字符串中的水果按照特定规则重新排列。我们可以使用Java来实现这个问题。 首先,我们需要定义一个函数来解决这个问题。 ```java public static String rearrangeFruits(String fruits) { // 将字符串转换为字符数组方便处理 char[] fruitArray = fruits.toCharArray(); // 统计每种水果的数量 int[] fruitCount = new int[26]; for (char fruit : fruitArray) { fruitCount[fruit - 'a']++; } // 创建一个新的字符数组来存储重新排列后的结果 char[] rearrangedFruitArray = new char[fruitArray.length]; // 逐个将水果按照规则放入新数组中 int index = 0; for (int i = 0; i < 26; i++) { while (fruitCount[i] > 0) { rearrangedFruitArray[index++] = (char) ('a' + i); fruitCount[i]--; } } // 将字符数组转换为字符串并返回 return new String(rearrangedFruitArray); } ``` 上述代码中,我们首先将字符串转换为字符数组,并使用一个长度为26的数组来统计每一种水果的数量。然后,我们创建一个新的字符数组来存储重新排列后的结果。 接下来,我们利用双重循环将每一种水果按照规则放入新数组中。最后,我们将字符数组转换为字符串并返回。 例如,如果输入字符串为`"acbba"`,则经过重新排列后,输出结果为`"aabbc"`。 这样,我们就用Java实现了题目要求的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值