Java 关于BFS算法的一个困惑

Java 关于BFS算法的一个困惑,java,graph,Java,Graph,以下代码用于遍历图形并打印顶点中的元素。。。但如果元素是数字,则此代码适用。。。。假设这些元素是字符串或字符。。。我可以对打印字符串或字符做哪些更改 import java.io.*; import java.util.*; // This class represents a directed graph using adjacency list // representation class Graph { private int V; // No. of ve

以下代码用于遍历图形并打印顶点中的元素。。。但如果元素是数字,则此代码适用。。。。假设这些元素是字符串或字符。。。我可以对打印字符串或字符做哪些更改

import java.io.*; 
import java.util.*; 
  
// This class represents a directed graph using adjacency list 
// representation 
class Graph 
{ 
    private int V;   // No. of vertices 
    private LinkedList<Integer> adj[]; //Adjacency Lists 
  
    // Constructor 
    Graph(int v) 
    { 
        V = v; 
        adj = new LinkedList[v]; 
        for (int i=0; i<v; ++i) 
            adj[i] = new LinkedList(); 
    } 
  
    // Function to add an edge into the graph 
    void addEdge(int v,int w) 
    { 
        adj[v].add(w); 
    } 
  
    // prints BFS traversal from a given source s 
    void BFS(int s) 
    { 
        // Mark all the vertices as not visited(By default 
        // set as false) 
        boolean visited[] = new boolean[V]; 
  
        // Create a queue for BFS 
        LinkedList<Integer> queue = new LinkedList<Integer>(); 
  
        // Mark the current node as visited and enqueue it 
        visited[s]=true; 
        queue.add(s); 
  
        while (queue.size() != 0) 
        { 
            // Dequeue a vertex from queue and print it 
            s = queue.poll(); 
            System.out.print(s+" "); 
  
            // Get all adjacent vertices of the dequeued vertex s 
            // If a adjacent has not been visited, then mark it 
            // visited and enqueue it 
            Iterator<Integer> i = adj[s].listIterator(); 
            while (i.hasNext()) 
            { 
                int n = i.next(); 
                if (!visited[n]) 
                { 
                    visited[n] = true; 
                    queue.add(n); 
                } 
            } 
        } 
    } 
import java.io.*;
导入java.util.*;
//此类使用邻接列表表示有向图
//代表
类图
{ 
私有int V;//顶点数
私有链接列表adj[];//邻接列表
//建造师
图形(INTV)
{ 
V=V;
adj=新链接列表[v];

对于(int i=0;i,如Szprota21所说,您需要将泛型合并到
图形中
类:

类图
{ 
私有int V;//顶点数
私有链接列表adj[];//邻接列表
//建造师
图形(INTV)
{ 
V=V;
adj=新链接列表[];

对于(int i=0;i不清楚您的问题是什么,为什么节点的内容很重要?如果您只想打印节点的内容,那么您只需要更改为,这样您就可以添加到队列中您想要的内容。但是如果您需要对内容执行更复杂的操作,那么您应该创建自己的类,这将是一个无法存储不同的类型并覆盖toString()方法。在此设置中,如何将T对象映射到数组索引?您可能希望从使用列表数组切换到类似于
映射的东西。这只是为了让它们从Integer以外的类型开始;我同意根据他的其他要求,需要进行更改。