Java实现无向图深度优先遍历广度优先遍历

import java.util.*;

/**
 * 图中节点值唯一标识这个节点
 *
 */

public class graphTest {

    static Map<Integer,LinkedList<Integer>> undirectedGraph = new LinkedHashMap<>();
    static Map<Integer,Boolean> visited = new HashMap();
    static Iterator<Map.Entry<Integer,LinkedList<Integer>>> it;
    /**
     * 递归深度优先遍历
     * @param start
     */
    static void DFS(Integer start){
        System.out.print(start+" ");
        visited.put(start,true);
        LinkedList<Integer>  neighbor = undirectedGraph.get(start);
        for(Integer i : neighbor){
            if(!visited.get(i)){
                DFS(i);
            }
        }
    }

    /**
     * 非递归深度优先遍历
     * @param start
     */
    static void DFSwithStack(Integer start){
        Stack<Integer> st = new Stack();
        System.out.print(start+" ");
        st.push(start);
        visited.put(start,true);
        while(!st.isEmpty()){
            int node = st.peek();
            LinkedList<Integer>  neighbor = undirectedGraph.get(node);
            boolean flag = false;
            if(neighbor.size() != 0) {
                for (Integer next : neighbor) {
                    if (!visited.get(next)) {
                        st.push(next);
                        System.out.print(next + " ");
                        visited.put(next, true);
                        flag = true;
                        break;
                    }
                }
            }
            if(!flag) {
                st.pop();
            }
        }
    }

    /**
     * 广度优先遍历
     */
    static void BFS(Integer start){
        Queue<Integer> q = new LinkedList();
        q.offer(start);
        System.out.print(start+" ");
        visited.put(start,true);
        while(!q.isEmpty()){
            int node = q.poll();
            LinkedList<Integer> neighbor = undirectedGraph.get(node);
            for(Integer i : neighbor){
                if(!visited.get(i)){
                    q.offer(i);
                    System.out.print(i+" ");
                    visited.put(i,true);
                }
            }
        }
    }

    static void initBeforeTravel(){
         Set<Integer> keys = visited.keySet();
         for(Integer key:keys){
             visited.put(key,false);
         }
        it = undirectedGraph.entrySet().iterator();
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入图中节点个数:");
        int sumOfNode = sc.nextInt();
        System.out.println("请输入图中" + sumOfNode + "个节点:");
        for(int i=0;i<sumOfNode;i++){
            int value = sc.nextInt();
            undirectedGraph.put(value,new LinkedList());
            visited.put(value,false);
        }
        System.out.println("请输入图中所有边:");

        String line = sc.nextLine();

        while(sc.hasNextLine()){
            line = sc.nextLine();
            if("".equals(line)){
                break;
            }
            String[] edge = line.split(" ");
            int node1 = Integer.parseInt(edge[0]);
            int node2 = Integer.parseInt(edge[1]);
            undirectedGraph.get(node1).add(node2);
            undirectedGraph.get(node2).add(node1);
        }

        initBeforeTravel();
        System.out.println("深度优先遍历序列:");
        while(it.hasNext()) {
            int start = it.next().getKey();
            if(!visited.get(start)) {
                DFS(start);
            }
        }

        initBeforeTravel();
        System.out.println("\n深度优先遍历序列:");
        while(it.hasNext()) {
            int start = it.next().getKey();
            if(!visited.get(start)) {
                DFSwithStack(start);
            }
        }

        initBeforeTravel();
        System.out.println("\n广度优先遍历序列:");
        while(it.hasNext()) {
            int start = it.next().getKey();
            if(!visited.get(start)) {
                BFS(start);
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是无向图深度优先遍历广度优先遍历的介绍和演示: 1.深度优先遍历(DFS): 深度优先遍历是一种用于遍历或搜索树或图的算法。在这种搜索方法,从根结点开始,尽可能深地搜索每个分支,直到找到目标值或无法继续为止。然后回溯到前一个结点,尝试另一条分支,直到所有结点都被访问为止。 以下是一个无向图深度优先遍历的Python代码示例: ```python # 无向图深度优先遍历 def DFS(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start, end=' ') for next in graph[start] - visited: DFS(graph, next, visited) return visited # 无向图的邻接表表示 graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} # 从顶点A开始遍历 print("深度优先遍历结果:") DFS(graph, 'A') ``` 输出结果为:A B D E F C 2.广度优先遍历(BFS): 广度优先遍历是一种用于遍历或搜索树或图的算法。在这种搜索方法,从根结点开始,逐层遍历每个分支,直到找到目标值或无法继续为止。 以下是一个无向图广度优先遍历的Python代码示例: ```python # 无向图广度优先遍历 def BFS(graph, start): visited, queue = set(), [start] visited.add(start) while queue: vertex = queue.pop(0) print(vertex, end=' ') for next in graph[vertex] - visited: visited.add(next) queue.append(next) # 无向图的邻接表表示 graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} # 从顶点A开始遍历 print("广度优先遍历结果:") BFS(graph, 'A') ``` 输出结果为:A B C D E F

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsws100

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值