第二十八天算法设计

Graph 类 (图的深度优先搜索)
java
package suanfa;

import java.util.Arrays;

public class Graph {
private int vertices; // 图的顶点数
private int[][] adjacencyMatrix; // 邻接矩阵

// 构造函数,初始化图
public Graph(int vertices) {
    this.vertices = vertices;
    adjacencyMatrix = new int[vertices][vertices]; // 创建邻接矩阵
}

// 向图中添加一条边
public void addEdge(int start, int end) {
    if (start >= 0 && start < vertices && end >= 0 && end < vertices) {
        adjacencyMatrix[start][end] = 1; // 从start到end有一条边
        adjacencyMatrix[end][start] = 1; // 因为是无向图,反向也添加边
    } else {
        System.out.println("输入的边的端点无效");
    }
}

// 深度优先搜索
public void dfs(int start) {
    boolean[] visited = new boolean[vertices]; // 记录各个节点是否已访问
    dfsHelper(start, visited);
}

// 深度优先搜索辅助方法
private void dfsHelper(int vertex, boolean[] visited) {
    // 打印当前访问的节点
    System.out.print(vertex + " ");
    visited[vertex] = true;

    // 访问与当前节点相邻的未访问的节点
    for (int i = 0; i < vertices; i++) {
        if (adjacencyMatrix[vertex][i] == 1 && !visited[i]) {
            dfsHelper(i, visited);
        }
    }
}

// 打印邻接矩阵
public void printGraph() {
    System.out.println("图的邻接矩阵:");
    for (int i = 0; i < vertices; i++) {
        for (int j = 0; j < vertices; j++) {
            System.out.print(adjacencyMatrix[i][j] + " ");
        }
        System.out.println();
    }
}

public static void main(String[] args) {
    // 创建一个图,图中有5个顶点
    Graph graph = new Graph(5);

    // 添加一些边
    graph.addEdge(0, 1);
    graph.addEdge(0, 4);
    graph.addEdge(1, 2);
    graph.addEdge(1, 3);
    graph.addEdge(3, 4);

    // 打印图的邻接矩阵
    graph.printGraph();

    // 执行深度优先搜索,从顶点0开始
    System.out.println("深度优先搜索结果:");
    graph.dfs(0);
}

}
录制: untitled2 – Insertion.java
录制文件:https://meeting.tencent.com/crm/KzGGkGE85d

posted @ 2025-02-10 19:03  申shen  阅读(54)  评论(0)    收藏  举报