图的邻接表存储及常见问题模板(java)
作者:
豪满天下
,
2020-04-08 11:14:24
,
所有人可见
,
阅读 1889
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int N = 100010;
static class Node{
int val;
int pos;
Node next;
}
static Node [] h = new Node[2*N];
static boolean [] visit = new boolean[2*N];
static void insert(int u,int p){
Node newNode = new Node(); newNode.pos = p;
newNode.next = h[u].next;
h[u].next = newNode;
}
static int dfstree(int u){
visit[u] = true;
int sum = 1;
Node hh = h[u];
while(hh.next!=null){
hh = hh.next;
if(!visit[hh.pos]){
sum += dfstree(hh.pos);
}
}
return sum;
}
static void dfs(int u){
visit[u] = true;
System.out.println(u);
Node hh = h[u];
while(hh.next!=null){
hh = hh.next;
if(!visit[hh.pos]){
dfs(hh.pos);
}
}
}
static void bfs(int u){
Queue<Integer> q = new LinkedList<Integer>();
q.add(u);
visit[u] = true;
int layer = 1;
while(!q.isEmpty()){
int n = q.size();
for(int i=0;i<n;i++){
int f = q.poll();
System.out.println("layer="+layer + "pos="+f);
Node hh = h[f];
while(hh.next!=null){
hh = hh.next;
if(!visit[hh.pos]){
visit[hh.pos] = true;
q.add(hh.pos);
}
}
}
layer++;
}
}
}