我正在做一个程序,从一个文本文件中获取顶点并创建一个图形。该代码接受一个带边的文本文件,使用邻接表数据结构构造一个图,然后最后使用深度优先搜索(DFS)来搜索图。
下面是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Graph {
private int V;
private ArrayList<Integer>[] adjList;
public Graph(int V) {
this.V = V;
adjList = new ArrayList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new ArrayList<Integer>();
}
}
public void addEdge(int u, int v) {
adjList[u].add(v);
}
public void DFS(int v, boolean[] visited) {
visited[v] = true;
System.out.print(v + " ");
for (int i = 0; i < adjList[v].size(); i++) {
int neighbor = adjList[v].get(i);
if (!visited[neighbor]) {
DFS(neighbor, visited);
}
}
}
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("input.txt"));
int V = scanner.nextInt();
Graph graph = new Graph(V);
while (scanner.hasNextInt()) {
int u = scanner.nextInt();
int v = scanner.nextInt();
graph.addEdge(u, v);
}
scanner.close();
for (int i = 0; i < V; i++) {
System.out.print(i + ": ");
for (int j = 0; j < graph.adjList[i].size(); j++) {
System.out.print(graph.adjList[i].get(j) + " ");
}
System.out.println();
}
Scanner userScanner = new Scanner(System.in);
System.out.print("Enter starting vertex: ");
int start = userScanner.nextInt();
userScanner.close();
boolean[] visited = new boolean[V];
System.out.println("DFS traversal from vertex " + start + ":");
graph.DFS(start, visited);
Scanner searchScanner = new Scanner(System.in);
System.out.print("\nEnter value to search for: ");
int value = searchScanner.nextInt();
searchScanner.close();
boolean[] searchVisited = new boolean[V];
System.out.println("Searching for value " + value + " starting from vertex " + start + ":");
boolean found = search(graph, start, value, searchVisited);
if (found) {
System.out.println("Value " + value + " found in the graph!");
} else {
System.out.println("Value " + value + " not found in the graph.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static boolean search(Graph graph, int v, int value, boolean[] visited) {
visited[v] = true;
if (v == value) {
return true;
}
for (int i = 0;graph.adjList[v].size(); i++) {
int neighbor = graph.adjList[v].get(i);
if (!visited[neighbor]) {
boolean found = search(graph, neighbor, value, visited);
if (found) {
return true;
}
}
}
return false;
}
}
该错误是公共静态布尔搜索中的for循环。我得到一个错误,说“类型不匹配:无法在graph.adjList[v].size()所在的位置将int转换为boolean”。
1条答案
按热度按时间bvjxkvbb1#
问题出在for循环中。
for
签名如下所示其中,
statement 1
执行一次statement 2
是决定循环是否必须再执行一次的条件statement 3
将在for块内的逻辑执行后执行在你的情况下
其中
statement 2
是一个int。你必须改变这一点,并提出条件。就像或者你需要什么