java广度优先遍历

冷不防 2022-04-02 13:42 312阅读 0赞
  1. /*
  2. 图的广度优先遍历
  3. 从1号顶点开始按照广度优先遍历顺序输出图G中的每个顶点,顶点编号间用一个空格间隔,每个无向图的输出占用一行,最后一行输出后换行。
  4. Sample Input
  5. 0 1 1 0 0
  6. 1 0 0 0 1
  7. 1 0 0 1 1
  8. 0 0 1 0 1
  9. 0 1 1 1 0
  10. Sample Output
  11. 1 2 3 5 4
  12. */
  13. public class BFSGraph {
  14. public static void bfs(int[][] matrix) {
  15. int[] visited = new int[matrix.length];
  16. ArrayQueue<Integer> queue = new ArrayQueue<>(matrix.length);
  17. int unviste;
  18. while ((unviste = getUnVisted(visited)) >= 0) {
  19. queue.put(unviste); //将当前未被访问节点状态改为已访问
  20. visited[unviste] = 1;
  21. System.out.print((unviste + 1) + "\t");
  22. while (!queue.isEmpty()) {
  23. Integer index = queue.poll(); //将刚刚被访问的节点依次出队,并广度搜索所有与出队的节点邻接的未被访问的节点
  24. for (int i = 0; i < matrix[index].length; i++) {
  25. //找到与当前出队的节点所有邻接的未被访问节点,访问该节点并入队
  26. if (index != i && visited[i] == 0 && matrix[index][i] > 0) {
  27. queue.put(i);
  28. visited[i] = 1;
  29. System.out.print((i + 1) + "\t");
  30. }
  31. }
  32. }
  33. }
  34. }
  35. public static void main(String[] args) {
  36. //图的邻接矩阵
  37. int[][] matrix = new int[][]{
  38. {0, 1, 1, 0, 0},
  39. {1, 0, 0, 0, 1},
  40. {1, 0, 0, 1, 1},
  41. {0, 0, 1, 0, 1},
  42. {0, 1, 1, 1, 0}};
  43. bfs(matrix);
  44. }
  45. public static int getUnVisted(int[] visited) {
  46. int index = -1;
  47. for (int i = 0; i < visited.length; i++) {
  48. if (visited[i] == 0) {
  49. index = i;
  50. break;
  51. }
  52. }
  53. return index;
  54. }
  55. private static class ArrayQueue<T> {
  56. public int front = 0, rear = 0;
  57. public Object[] array;
  58. private int capacity = 8;//队列的默认容量
  59. public ArrayQueue(int capacity) {
  60. this.array = new Object[capacity];
  61. this.capacity = capacity;
  62. }
  63. public ArrayQueue() {
  64. array = new Object[capacity];
  65. }
  66. public void put(T data) {
  67. if (rear >= capacity) {
  68. addStackCapacity();
  69. }
  70. array[rear] = data;
  71. rear++;
  72. }
  73. public T peek() {
  74. if (isEmpty()) {
  75. return null;
  76. }
  77. return (T) array[front];
  78. }
  79. public T poll() {
  80. if (isEmpty()) {
  81. return null;
  82. }
  83. T t = (T) array[front];
  84. array[front] = null;
  85. front++;
  86. return t;
  87. }
  88. public boolean isEmpty() {
  89. return front == rear;
  90. }
  91. public int size() {
  92. return rear - front;
  93. }
  94. public void addStackCapacity() {
  95. if (front > 0) {
  96. System.arraycopy(this.array, front, this.array, 0, this.size());
  97. rear -= front;
  98. front = 0;
  99. } else {
  100. this.capacity = this.capacity * 2;
  101. Object[] newArray = new Object[this.capacity];
  102. System.arraycopy(this.array, 0, newArray, 0, this.array.length);
  103. this.array = newArray;
  104. }
  105. }
  106. }
  107. }

发表评论

表情:
评论列表 (有 0 条评论,312人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java广度优先

    / 图的广度优先遍历 从1号顶点开始按照广度优先遍历顺序输出图G中的每个顶点,顶点编号间用一个空格间隔,每个无向图的输出占用一行,最