吝啬的国度_链表

本文介绍了一个使用Java实现的链表遍历算法,包括深度优先搜索(DFS)和广度优先搜索(BFS)。该算法通过构建边的数据结构来实现节点之间的连接,并演示了如何对链表进行遍历来寻找路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package 搜索;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;


public class 吝啬的国度_链表 {
static class Edge {
public int next;
public Edge e;
}


static int result[];
static boolean visited[];
static int m;
static int s;
static ArrayList<Edge> arr;


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0) {
m = sc.nextInt();
s = sc.nextInt();
arr = new ArrayList<Edge>();
visited = new boolean[m + 1];
result = new int[m + 1];
for (int i = 0; i <= m; i++) {
arr.add(null);
}
int i, a, b;
Edge edge;
for (i = 0; i < m - 1; i++) {
a = sc.nextInt();
b = sc.nextInt();


edge = new Edge();
edge.next = b;
edge.e = arr.get(a);
arr.set(a, edge);


edge = new Edge();
edge.next = a;
edge.e = arr.get(b);
arr.set(b, edge);
}


visited[s] = true;
dfs(s);
bfs();
result[s] = -1;
for (i = 1; i <= m; i++) {
System.out.print(result[i] + " ");
}
}
}


private static void bfs() {
Queue<Integer> que = new LinkedList<Integer>();
que.add(s);
while (!que.isEmpty()) {
Integer poll = que.poll();
Edge edge = arr.get(poll);
while (edge != null) {
int next = edge.next;
if (!visited[next]) {
visited[next] = true;
result[next] = poll;
que.add(next);
}
edge = edge.e;
}
}


}


private static void dfs(int s) {
Edge edge = arr.get(s);
while (edge != null) {
int next = edge.next;
if (!visited[next]) {
visited[next] = true;
dfs(next);
}
result[next] = s;
edge = edge.e;
}


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值