diff --git a/Graph.java b/Graph.java new file mode 100644 index 0000000000000000000000000000000000000000..6c40890cf3925ef5c0a569fd14cf15c592a8cdd3 --- /dev/null +++ b/Graph.java @@ -0,0 +1,83 @@ +package datastruct.graph; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class Graph { + boolean[][] arr = new boolean[5][5]; + LinkedList list = new LinkedList<>(); + ArrayList deepList = new ArrayList(); + + Graph() { + //邻接矩阵,长度为 + arr[0][2] = true; + arr[0][1] = true; + arr[1][3] = true; + arr[2][3] = true; + arr[1][4] = true; + //邻接表表示法 + boolean[] temp; + for (int i = 0; i < 6; i++) { + temp = new boolean[]{false, false, false, false, false}; + list.add(temp); + } + temp = new boolean[]{false, true, true, false, false}; + list.set(0, temp); + temp = new boolean[]{false, false, false, true, true}; + list.set(1, temp); + temp = new boolean[]{false, false, false, true, false}; + list.set(2, temp); + for (int i = 0; i < arr.length; i++) { + deepList.add(false); + } + } + + //深度遍历 + public void deep(boolean[] temp, int index) { + //设置一个布尔值array来存放 元素是否遍历过 + if (deepList.get(index)) { + return; + } else { + //没有遍历过,输出,并且设置为遍历过 + System.out.print(index + " "); + deepList.set(index, true); + //循环查看该元素是否有连接其他元素,递归调用 直至最后一个节点 + for (int i = 0; i < temp.length; i++) { + if (temp[i]) { + deep(list.get(i), i); + } + } + } + } + + //层次遍历 + public void level() { + //设置一个队列来存放节点,一个布尔arr来存放元素是不是已经遍历过 + Queue queue = new ArrayDeque<>(); + ArrayList tempList = new ArrayList(); + for (int i = 0; i < 6; i++) { + tempList.add(false); + } + if (queue.isEmpty()) { + queue.offer(0); + tempList.set(0, true); + } + while (!queue.isEmpty()) { + //出队 + int temp = queue.poll(); + //判断该出队的节点是否有连接其他元素,若是连接了其他节点,且其他节点还没被遍历,就把该就节点入队,并且设置为遍历过 + for (int i = 0; i < list.get(temp).length; i++) { + if (list.get(temp)[i]) { + if (!tempList.get(i)) { + queue.offer(i); + tempList.set(i, true); + } + } + } + System.out.print(temp + " "); + } + } + +} diff --git a/Test.java b/Test.java new file mode 100644 index 0000000000000000000000000000000000000000..dea0c9d4c91df385aab549327c4f2c1249773775 --- /dev/null +++ b/Test.java @@ -0,0 +1,18 @@ +package datastruct.graph; + +public class Test { + public static void main(String[] args) { + /*测试图的邻接矩阵: + 0 1 1 0 0 + 0 0 0 1 1 + 0 0 0 1 0 + 0 0 0 0 0 + 0 0 0 0 0 + */ + Graph graph = new Graph(); + System.out.print("深度遍历:"); + graph.deep(graph.list.get(0), 0); + System.out.print("\n广度优先遍历:"); + graph.level(); + } +}