1
그래서 나는 java를 사용하여 무향 그래프에서 경로를 찾으려고합니다. 나는 내가 옳은 길에있을 것 같은 느낌이 든다. 그러나 그것을 얻기에 꽤 가깝다. 그러나 나는 도로 블록으로 계속 달려가는데 오류가 발생한다. 나는 가장자리와 꼭지점을 저장하기 위해 연결된리스트를 사용하고있다.링크 된 목록 일반 배열 생성 오류 undirected graph Java
Graph2.java:17: error: generic array creation adj = new LinkedList[v];
여기 내 코드의
import java.io.*;
import java.util.*;
import java.util.LinkedList;
import java.util.Scanner;
// This class represents a directed graph using adjacency list
// representation
class Graph2
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency List
//Constructor
Graph2(int v)
{
V = v;
adj = new LinkedList<Integer>[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList<Integer>();
}
//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
Boolean isReachable(int s, int d)
{
LinkedList<Integer>temp;
// 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);
// 'i' will be used to get all adjacent vertices of a vertex
Iterator<Integer> i;
while (queue.size()!=0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
int n;
i = adj[s].listIterator();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
while (i.hasNext())
{
n = i.next();
System.out.println(n);
// If this adjacent node is the destination node,
// then return true
if (n==d)
return true;
// Else, continue to do BFS
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
// If BFS is complete without visited d
return false;
}
// Driver method
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g = new Graph(9999999);
try{
File file = new File("Graph.txt");
Scanner scan = new Scanner(file);
while(scan.hasNextLine())
{
String [] tempArray = scan.nextLine().split(",");
g.addEdge(Integer.parseInt(tempArray[0]), Integer.parseInt(tempArray[1]));
}
scan.close();
}
catch(FileNotFoundException fs)
{
}
int u = 1;
int v = 891950;
if (g.isReachable(u, v))
System.out.println("There is a path from " + u +" to " + v);
else
System.out.println("There is no path from " + u +" to " + v);;
}
}