简体   繁体   English

关于 BFS 算法的困惑

[英]A confusion about BFS algorithm

The following code is used to traverse a graph and print the elements in vertices ... but this code is suitable if the elements are numbers .... suppose that these elements are string or characters ... what changes can I do to print string or characters以下代码用于遍历图形并打印顶点中的元素……但是如果元素是数字,则此代码适用……假设这些元素是字符串或字符……我可以做哪些更改来打印字符串或字符

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); 
                } 
            } 
        } 
    } 

Like Szprota21 says you need to incorporate generics into your Graph class:就像 Szprota21 说你需要将泛型合并到你的Graph类中:

class Graph<T> 
{ 
    private int V;   // No. of vertices 
    private LinkedList<T> adj[]; //Adjacency Lists 
  
    // Constructor 
    Graph(int v) 
    { 
        V = v; 
        adj = new LinkedList<T>[]; 
        for (int i=0; i<v; ++i) 
            adj[i] = new LinkedList<T>(); 
    } 

    // Continue using T

Which allows you to use:这允许您使用:

Graph<Integer> intgraph = new Graph<Integer>(5);
Graph<String> intgraph = new Graph<String>(5);
Graph<Character> intgraph = new Graph<Character>(5);

And just like previously mentioned use:就像前面提到的使用:

T value = queue.poll();
value.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM