LeetCode-DFS-图类-中等难度

547.省份数量

在这里插入图片描述

本题实际上就是求解图的连通分量个数。

public int findCircleNum(int[][] isConnected) {
    int ans = 0;
    int cities = isConnected.length;
    boolean[] visited = new boolean[cities];
    for (int i = 0; i < cities; i++) {
        if (!visited[i]) {
            visited[i] = true;
            dfs(isConnected, cities, i, visited);
            ans++;
        }
    }
    return ans;
}

private void dfs(int[][] isConnected, int cities, int idx, boolean[] visited) {
    for (int i = 0; i < cities; i++) {
        if (isConnected[idx][i] == 1 && !visited[i]) {
            visited[i] = true;
            dfs(isConnected, cities, i, visited);
        }
    }
}

1971.寻找图中是否存在路径

在这里插入图片描述

这是一道经典的求图中两个点是否连通的问题,直接使用邻接表法进行构图,然后从source开始遍历即可。

public boolean validPath(int n, int[][] edges, int source, int destination) {
    List<List<Integer>> edgeList = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        edgeList.add(new ArrayList<>());
    }
    for (int i = 0; i < edges.length; i++) {
        int s = edges[i][0];
        int d = edges[i][1];
        edgeList.get(s).add(d);
        edgeList.get(d).add(s);
    }
    boolean[] visited = new boolean[n];
    return dfs(edgeList, source, destination, visited);
}
private boolean dfs(List<List<Integer>> edgeList, int source, int destination, boolean[] visited) {
    if (source == destination) {
        return true;
    }
    visited[source] = true;
    for (int next : edgeList.get(source)) {
        if (!visited[next] && dfs(edgeList, next, destination, visited)) {
            return true;
        }
    }
    return false;
}

797.所有可能的路径

在这里插入图片描述

一道回溯算法的应用题

public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    dfs(ans, path, graph[0], 0, graph);
    return ans;
}
private void dfs(List<List<Integer>> ans, List<Integer> path, int[] arr, int idx, int[][] graph) {
    path.add(idx);
    if (idx == graph.length - 1) {
        ans.add(new ArrayList<>(path));
        return;
    }
    for (int i : arr) {
        dfs(ans, path, graph[i], i, graph);
        path.remove(path.size() - 1);
    }
}

841.钥匙和房间

在这里插入图片描述

本题实际上就是求解从顶点0开始,能否达到图中的所有点,所以本质上从0开始遍历,结束后检查下是否所有点都被访问过即可。

class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        int len = rooms.size();
        boolean[] visited = new boolean[len];
        dfs(visited, rooms, 0);
        for (int i = 0; i < visited.length; i++) {
            if (!visited[i]) {
                return false;
            }
        }
        return true;
    }

    private void dfs(boolean[] visited, List<List<Integer>> rooms, int idx) {
        visited[idx] = true;
        for (int next : rooms.get(idx)) {
            if (!visited[next]) {
                visited[idx] = true;
                dfs(visited, rooms, next);
            }
        }
    }  
}

2316.统计无向图中无法互相到达点对数
在这里插入图片描述

统计每个连通分量的大小,多个连通分量之间大小乘积之和即为结果。

public long countPairs(int n, int[][] edges) {
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        graph.add(new ArrayList<>());
    }
    for (int[] e : edges) {
        graph.get(e[0]).add(e[1]);
        graph.get(e[1]).add(e[0]);
    }
    boolean[] visited = new boolean[n];
    long ans = 0;
    int total = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            int size = dfs(visited, graph, i);
            ans += (long) total * size;
            total += size;
        }
    }
    return ans;
}

private int dfs(boolean[] visited, List<List<Integer>> graph, int idx) {
    visited[idx] = true;
    int size = 1;
    for (int next : graph.get(idx)) {
        if (!visited[next]) {
            size += dfs(visited, graph, next);
        }
    }
    return size;
}

2492.两个城市间路径的最小分数

在这里插入图片描述

从编号为1的城市开始,把所有的连通城市都遍历一次,找出最小的距离即可。

public int minScore(int n, int[][] roads) {
    List<int[]>[] graph = new ArrayList[n + 1];
    for (int i = 1; i <= n; i++) {
        graph[i] = new ArrayList<>();
    }
    for (int[] r : roads) {
        int a = r[0];
        int b = r[1];
        int d = r[2];
        graph[a].add(new int[]{b, d});
        graph[b].add(new int[]{a, d});
    }
    boolean[] visited = new boolean[n + 1];
    return dfs(graph, visited, 1);
}

private int dfs(List<int[]>[] graph, boolean[] visited, int idx) {
    visited[idx] = true;
    int min = Integer.MAX_VALUE;
    for (int[] next : graph[idx]) {
        min = Math.min(min, next[1]);
        if (!visited[next[0]]) {
            min = Math.min(min, dfs(graph, visited, next[0]));
        }

    }
    return min;
}

2685.统计完全连通分量的数量

在这里插入图片描述

在完全连通分量中,点集的大小与边集的大小关系应该是,边集大小 = 点集大小 * (点集大小 - 1) ÷ 2
因此,只需要求出每个连通分量中点集和边集的大小即可。

class Solution {
    
    int e = 0;
    int v = 0;
    
    public int countCompleteComponents(int n, int[][] edges) {
        List<int[]>[] graph = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int[] e : edges) {
            graph[e[0]].add(new int[]{e[1]});
            graph[e[1]].add(new int[]{e[0]});
        }
        boolean[] visited = new boolean[n];
        int ans = 0;
        for (int i = 0; i < n; i++) {
            e = 0;
            v = 0;
            if (!visited[i]) {
                dfs(graph, visited, i);
                if (e == v * (v - 1)) {
                    ans++;
                }
            }
        }
        return ans;
    }

    // 如果是完全连通分量,则每个点都应该与所有点能直接连通。
    // 所以,通过graph[idx].size(),即可得到能与其直接连通的点的数量。
    // 注意:因为每个点都加了一次graph[idx].size(),相当于多加了一倍,
    // 所以在判断边集与点集的关系时直接用了e == v * (v - 1) 等价于 e/2 == (v * (v - 1))/2
    private void dfs(List<int[]>[] graph, boolean[] visited, int idx) {
        visited[idx] = true;
        v++;
        e += graph[idx].size();
        for (int[] next : graph[idx]) {
            if (!visited[next[0]]) {
                dfs(graph, visited, next[0]);
            }
        }
    }
}
  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
LeetCode-Editor是一种在线编码工具,它提供了一个用户友好的界面编写和运行代码。在使用LeetCode-Editor时,有时候会出现乱码的问题。 乱码的原因可能是由于编码格式不兼容或者编码错误导致的。在这种情况下,我们可以尝试以下几种解决方法: 1. 检查文件编码格式:首先,我们可以检查所编辑的文件的编码格式。通常来说,常用的编码格式有UTF-8和ASCII等。我们可以将编码格式更改为正确的格式。在LeetCode-Editor中,可以通过界面设置或编辑器设置来更改编码格式。 2. 使用正确的字符集:如果乱码是由于使用了不同的字符集导致的,我们可以尝试更改使用正确的字符集。常见的字符集如Unicode或者UTF-8等。在LeetCode-Editor中,可以在编辑器中选择正确的字符集。 3. 使用合适的编辑器:有时候,乱码问题可能与LeetCode-Editor自身相关。我们可以尝试使用其他编码工具,如Text Editor、Sublime Text或者IDE,看是否能够解决乱码问题。 4. 查找特殊字符:如果乱码问题只出现在某些特殊字符上,我们可以尝试找到并替换这些字符。通过仔细检查代码,我们可以找到导致乱码的特定字符,并进行修正或替换。 总之,解决LeetCode-Editor乱码问题的方法有很多。根据具体情况,我们可以尝试更改文件编码格式、使用正确的字符集、更换编辑器或者查找并替换特殊字符等方法来解决这个问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值