是给了邻接矩阵然后转成邻接表的情况
bfs
class Scratch { static int[][] adjMatrix = new int[][]{ {0,1,1,0,0,0,0,0}, {1,0,0,1,1,0,0,0}, {1,0,0,0,0,1,1,0}, {0,1,0,0,0,0,0,1}, {0,1,0,0,0,0,0,1}, {0,0,1,0,0,0,1,0}, {0,0,1,0,0,1,0,0}, {0,0,0,1,1,0,0,0}}; static boolean[] viss=new boolean[adjMatrix.length]; static ArrayList <ArrayList<Integer>> graph=new ArrayList<>(); static void bfs(int n){ Deque<Integer> que=new ArrayDeque<>(); viss[n]=true; que.offerFirst(n); while (que.size()!=0){ Integer cur=que.pollFirst(); System.out.print(cur+1+" "); for (int nextnode : graph.get(cur)) { if (!viss[nextnode]) { que.offerLast(nextnode); viss[nextnode] = true; } } } } public static void main(String[] args) { for (int i=0;i<adjMatrix.length;i++) { graph.add(new ArrayList<>()); for (int j=0;j<adjMatrix[i].length;j++){ if (adjMatrix[i][j]!=0) graph.get(i).add(j); } } int start=3; bfs(start-1); } }
dfs
class Scratch { static int[][] adjMatrix = new int[][]{ {0,1,1,0,0,0,0,0}, {1,0,0,1,1,0,0,0}, {1,0,0,0,0,1,1,0}, {0,1,0,0,0,0,0,1}, {0,1,0,0,0,0,0,1}, {0,0,1,0,0,0,1,0}, {0,0,1,0,0,1,0,0}, {0,0,0,1,1,0,0,0}}; static boolean[] viss=new boolean[adjMatrix.length]; static ArrayList <ArrayList<Integer>> graph=new ArrayList<>(); static void dfs(int n){ if (viss[n]) return; viss[n]=true; System.out.print(n+1+" "); for (int nextnode : graph.get(n)) { if (!viss[nextnode]) dfs(nextnode); } } public static void main(String[] args) { for (int i=0;i<adjMatrix.length;i++) { graph.add(new ArrayList<>()); for (int j=0;j<adjMatrix[i].length;j++){ if (adjMatrix[i][j]!=0) graph.get(i).add(j); } } int start=1; dfs(start-1); } }