BFS & DFS(Java实现)

  • 类似于树按层次遍历的过程
  • 要求顺次访问
  • 为了顺次访问路径长度为2、3、…的顶点,需要使用队列记录已访问的顶点
  • 时间复杂度:O(n + e)
    e为无向图中边的数或有向图中弧的数
    /**
     * Broadth First Search
     * @param graph 用于存放图中每个结点的邻接表
     *              key:Character value:该结点的邻接表 LinkedList<Character>
     * @param map 用于存放每个结点与顶点的距离
     *            key:Character value:距离
     * @param start 起始顶点
     */
    public void BFS(HashMap<Character, LinkedList<Character>> graph,
                    HashMap<Character, Integer> map,
                    char start) {

        Queue<Character> q = new LinkedList<>();
        q.add(start); //将起始顶点加入队列
        map.put(start, 0);

        int i = 0;

        while (!q.isEmpty()) {
            //取出队首元素
            char top = q.poll();

            i++;
            System.out.println("The" + i +"th element: " + top + "Distance from start is: " + map.get(top));

            //计算周边未访问过的结点的距离
            int distance = map.get(top) + 1;

            //访问队首元素结点的邻接表
            for (Character c : graph.get(top)) {

                //在该邻接表中,如果某元素还没被访问到,说明还未遍历,则访问这个结点
                if (!map.containsKey(c)){
                    map.put(c, distance);
                    q.add(c);
                }
            }
        }
    }
  • 可以快速发现底部元素
  • 时间复杂度:O(n + e)
    e为无向图中边的数或有向图中弧的数
    static int count = 0;

    /**
     * Broadth First Search
     * @param graph 用于存放图中每个结点的邻接表
     *              key:Character value:该结点的邻接表 LinkedList<Character>
     * @param visited 用于存放每个结点与顶点的距离
     *            key:Character value:距离
     * @param start 起始顶点
     */
    public void DFS(HashMap<Character, LinkedList<Character>> graph,
                    HashMap<Character, Boolean> visited,
                    char start) {
        visit(graph, visited, 's');
    }

    private static void visit(HashMap<Character, LinkedList<Character>> graph,
                              HashMap<Character, Boolean> visited,
                              char start) {
        if (!visited.containsKey(start)) {
            count++;
            //记录进入该结点的时间
            System.out.println("The time into element: " + start + ":" + count);
            //将该结点标志为已访问
            visited.put(start, true);

            //访问队首元素结点的邻接表
            for (char c : graph.get(start)) {
                //递归访问其他邻近结点
                if (!visited.containsKey(c)) {
                    visit(graph, visited, c);
                }
            }
            count++;
            System.out.println("The time out element: " + start + ":" + count);
        }
    }
### Java矩阵上BFSDFS实现 #### 广度优先搜索 (BFS) 广度优先搜索是一种逐层遍历的方式,通常借助队列来实现。以下是基于矩阵的BFS实现: ```java import java.util.LinkedList; import java.util.Queue; public class BFS { public void bfsTraversing(int[][] matrix, boolean[] visited, int startNode) { Queue&lt;Integer&gt; queue = new LinkedList&lt;&gt;(); queue.add(startNode); visited[startNode] = true; while (!queue.isEmpty()) { int currentNode = queue.poll(); System.out.print(currentNode + &quot; &quot;); for (int i = 0; i &lt; matrix.length; i++) { if (matrix[currentNode][i] == 1 &amp;&amp; !visited[i]) { queue.add(i); visited[i] = true; } } } } public static void main(String[] args) { int[][] adjacencyMatrix = { {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0} }; boolean[] visited = new boolean[adjacencyMatrix.length]; BFS bfs = new BFS(); bfs.bfsTraversing(adjacencyMatrix, visited, 0); // 输出节点访问顺序 } } ``` 上述代码展示了如何通过邻接矩阵表示图并执行BFS操作[^1]。 --- #### 深度优先搜索 (DFS) 深度优先搜索采用递归方式或栈结构完成遍历过程。下面是基于矩阵的DFS实现: ```java public class DFS { public void dfsTraversing(int node, int[][] graph, boolean[] visited) { visited[node] = true; System.out.print(node + &quot; &quot;); for (int i = 0; i &lt; graph.length; i++) { if (graph[node][i] == 1 &amp;&amp; !visited[i]) { dfsTraversing(i, graph, visited); } } } public static void main(String[] args) { int[][] adjacencyMatrix = { {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 1, 0} }; boolean[] visited = new boolean[adjacencyMatrix.length]; DFS dfs = new DFS(); dfs.dfsTraversing(0, adjacencyMatrix, visited); // 输出节点访问顺序 } } ``` 此代码片段实现了利用递归方式进行DFS的操作[^3]。 --- 对于LeetCode中的图像渲染问题,可以结合BFS/DFS解决二维数组的相关题目。例如给定初始坐标 `(sr, sc)` 和新颜色 `newColor`,可以通过修改像素值达到渲染效果[^2]。 ```java class Solution { private final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; public int[][] floodFill(int[][] image, int sr, int sc, int color) { if (image[sr][sc] == color) return image; fill(image, sr, sc, image[sr][sc], color); return image; } private void fill(int[][] image, int r, int c, int oldColor, int newColor) { if (r &lt; 0 || r &gt;= image.length || c &lt; 0 || c &gt;= image[0].length || image[r][c] != oldColor) return; image[r][c] = newColor; for (int[] dir : directions) { fill(image, r + dir[0], c + dir[1], oldColor, newColor); } } } ``` 以上代码展示了一个典型的DFS应用案例&mdash;&mdash;填充指定区域的颜色。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值