Day48 | 107.寻找存在的路径

2024-08-27 13:12
文章标签 路径 存在 107 寻找 day48

本文主要是介绍Day48 | 107.寻找存在的路径,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

语言

Java

107.寻找存在的路径

题目

107. 寻找存在的路径

题目描述

给定一个包含 n 个节点的无向图中,节点编号从 1 到 n (含 1 和 n )。

你的任务是判断是否有一条从节点 source 出发到节点 destination 的路径存在。

输入描述

第一行包含两个正整数 N 和 M,N 代表节点的个数,M 代表边的个数。 

后续 M 行,每行两个正整数 s 和 t,代表从节点 s 与节点 t 之间有一条边。 

最后一行包含两个正整数,代表起始节点 source 和目标节点 destination。

输出描述

输出一个整数,代表是否存在从节点 source 到节点 destination 的路径。如果存在,输出 1;否则,输出 0。

思路

  1. 初始化并查集
    • 创建一个大小为n+1的数组father,其中n是节点的数量。每个位置i的值初始化为i,表示每个节点最初都是自己的根节点。
  2. 处理边的连接
    • 读入每条边的两个端点st,然后调用join(s, t)方法来合并这两个节点所在的集合。
  3. 判断连通性
    • 对于给定的源节点source和目标节点destination,分别找到它们各自的根节点,如果这两个根节点相同,则表示这两个节点是连通的。

代码

import java.util.Scanner;
import java.util.Arrays;public class Main {private static int n; // Number of nodesprivate static int[] father; // Parent array initialized to store parent for each nodepublic static void main(String[] args) {Scanner scanner = new Scanner(System.in);n = scanner.nextInt(); // Read the number of nodesint m = scanner.nextInt(); // Read the number of edgesinit(n); // Initialize the union-find data structurewhile (m-- > 0) {int s = scanner.nextInt();int t = scanner.nextInt();join(s, t); // Join the two nodes}int source = scanner.nextInt();int destination = scanner.nextInt();System.out.println(isSame(source, destination) ? 1 : 0); // Check if source and destination are in the same setscanner.close();}// Initializes the parent array with the nodes themselvesprivate static void init(int n) {father = new int[n + 1];Arrays.fill(father, -1); // Initialize all parents to -1for (int i = 1; i <= n; i++) {father[i] = i; // Each node is its own parent initially}}// Finds the root of the set that contains node 'u'private static int find(int u) {return u == father[u] ? u : (father[u] = find(father[u])); // Path compression}// Checks if nodes 'u' and 'v' belong to the same setprivate static boolean isSame(int u, int v) {return find(u) == find(v);}// Merges the sets containing nodes 'u' and 'v'private static void join(int u, int v) {u = find(u); // Find the root of the set containing uv = find(v); // Find the root of the set containing vif (u == v) return; // If they are already in the same set, do nothingfather[v] = u; // Make the root of v point to the root of u}
}

易错点

  1. 初始化时的赋值

    • 在初始化时,每个节点的父节点应被设为它自己。在Java中,可以先使用Arrays.fill(father, -1)将数组填充为-1,然后再遍历数组将每个位置设为它自己。这样做是为了避免负数作为节点编号的情况。
  2. 路径压缩

    • find方法中,使用了路径压缩技术,即在递归查找根节点的过程中更新每个节点的父节点,使其直接指向根节点。这样可以提高查找效率。
  3. 循环条件

    • 在处理边的循环中,使用while (m-- > 0),这里m--意味着每次循环后m的值减1。这是一个常见的写法,但需要注意不要在循环外部再对m进行操作,否则可能会导致逻辑错误。
  4. 边界情况

    • join方法中,如果两个节点已经是同一个集合中的成员,则不需要做任何操作。这可以通过检查两个节点的根节点是否相同来实现。

总结

今天学了并查集理论

应用完成了一道题

明天继续图论继续加油!

天道酬勤

这篇关于Day48 | 107.寻找存在的路径的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1111769

相关文章

python 字典d[k]中key不存在的解决方案

《python字典d[k]中key不存在的解决方案》本文主要介绍了在Python中处理字典键不存在时获取默认值的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录defaultdict:处理找不到的键的一个选择特殊方法__missing__有时候为了方便起见,

如何测试计算机的内存是否存在问题? 判断电脑内存故障的多种方法

《如何测试计算机的内存是否存在问题?判断电脑内存故障的多种方法》内存是电脑中非常重要的组件之一,如果内存出现故障,可能会导致电脑出现各种问题,如蓝屏、死机、程序崩溃等,如何判断内存是否出现故障呢?下... 如果你的电脑是崩溃、冻结还是不稳定,那么它的内存可能有问题。要进行检查,你可以使用Windows 11

python获取当前文件和目录路径的方法详解

《python获取当前文件和目录路径的方法详解》:本文主要介绍Python中获取当前文件路径和目录的方法,包括使用__file__关键字、os.path.abspath、os.path.realp... 目录1、获取当前文件路径2、获取当前文件所在目录3、os.path.abspath和os.path.re

hdu2544(单源最短路径)

模板题: //题意:求1到n的最短路径,模板题#include<iostream>#include<algorithm>#include<cstring>#include<stack>#include<queue>#include<set>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#i

poj 1734 (floyd求最小环并打印路径)

题意: 求图中的一个最小环,并打印路径。 解析: ans 保存最小环长度。 一直wa,最后终于找到原因,inf开太大爆掉了。。。 虽然0x3f3f3f3f用memset好用,但是还是有局限性。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#incl

寻找身高相近的小朋友

题目描述: 小明今年升学到小学一年级,来到新班级后发现其他小朋友们身高参差不齐,然后就想基于各小朋友和自己的身高差对他们进行排序,请帮他实现排序。 输入描述: 第一行为正整数H和N,0<H<200,为小明的身高,0<N<50,为新班级其他小朋友个数。第二行为N个正整数H1-HN,分别是其他小朋友的身高,取值范围0<Hi<200(1<=i<=N),且N个正整数各不相同。 输出描述: 输出

easyui同时验证账户格式和ajax是否存在

accountName: {validator: function (value, param) {if (!/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/i.test(value)) {$.fn.validatebox.defaults.rules.accountName.message = '账户名称不合法(字母开头,允许4-16字节,允许字母数字下划线)';return fal

【408DS算法题】039进阶-判断图中路径是否存在

Index 题目分析实现总结 题目 对于给定的图G,设计函数实现判断G中是否含有从start结点到stop结点的路径。 分析实现 对于图的路径的存在性判断,有两种做法:(本文的实现均基于邻接矩阵存储方式的图) 1.图的BFS BFS的思路相对比较直观——从起始结点出发进行层次遍历,遍历过程中遇到结点i就表示存在路径start->i,故只需判断每个结点i是否就是stop

Android Environment 获取的路径问题

1. 以获取 /System 路径为例 /*** Return root of the "system" partition holding the core Android OS.* Always present and mounted read-only.*/public static @NonNull File getRootDirectory() {return DIR_ANDR

图的最短路径算法——《啊哈!算法》

图的实现方式 邻接矩阵法 int[][] map;// 图的邻接矩阵存储法map = new int[5][5];map[0] = new int[] {0, 1, 2, 3, 4};map[1] = new int[] {1, 0, 2, 6, 4};map[2] = new int[] {2, 999, 0, 3, 999};map[3] = new int[] {3, 7