图的遍历 非递归

图的遍历与树的遍历是一样的,这里我就不详细的讲了。

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Graph {
    int[][] graph;

    public Graph(int[][] graph) {
        this.graph = graph;
    }
    public void printGraph(){
        for(int[] array:graph){
            for(int temp:array){
                System.out.print(temp+"  ");
            }
            System.out.println();
        }
    }
    public void dfs(){
        // 我们需要有个book来记录已经读过的值
        boolean[] book = new boolean[graph.length];
        int readLength = 0;
        // 我们需要有个stack 记录我们的push
        Stack<Integer> stack = new Stack<>();

        while (readLength!= graph.length){
            if(stack.isEmpty()){
                for(int i=0;i<book.length;i++){
                    if(!book[i]){
                        stack.push(i);
                        break;
                    }
                }
            }
            int index = stack.pop();
            book[index] = true;
            readLength++;
            System.out.print(index+1+" ");
            for(int i=0;i<graph.length;i++){
                if(graph[index][i]==1&&!book[i]){
                    stack.push(i);
                }
            }
        }
        System.out.println();
    }
    public void bfs(){
        boolean[] visited = new boolean[graph.length];
        Queue<Integer> queue = new LinkedList<>();
        int readLen = 0;
        while (readLen!=graph.length){
            if (queue.isEmpty()){
                for(int i=0;i<visited.length;i++){
                    if(!visited[i]){
                        queue.offer(i);
                        break;
                    }
                }
            }
            int node = queue.poll();
            System.out.print(node+1+" ");
            visited[node] = true;
            readLen++;
            for(int i=0;i<graph.length;i++){
                if(graph[node][i]==1&&!visited[i]){
                    queue.offer(i);
                }
            }
        }
        System.out.println();
    }
}
class testgraph{
    public static void main(String[] args) {
        int[][] arrays = {{0,1,0,1,0},{1,0,1,0,1},{0,1,0,1,1},{1,0,1,0,0},{0,1,1,0,0}};
        Graph graph = new Graph(arrays);
        graph.printGraph();
        graph.dfs();

        graph.bfs();
    }
}
上一篇:xctf的一道题目(77777)


下一篇:151. Reverse Words in a String翻转一句话中的单词