我在使用DFS时遇到了麻烦,它发出了错误的遍历。我还需要第一次遇到DFS并保存它以便以后打印。第一次遭遇将是1 2 6 7 4 3 5 8
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
public class DFS {
private Stack<Integer> stack;
String line;
int row = 0;
static int size = 0;
public DFS(){
stack = new Stack<Integer>();
}
public void dfs(int adjMatrix[][], int vert)
{
int number_of_nodes = adjMatrix[vert].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = vert;
int i = vert;
System.out.println(element + "\t");
visited[vert] = 1;
stack.push(vert);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjMatrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + "\t");
continue;
}
i++;
}
stack.pop();
}
}
public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {
int[][] matrix = null;
BufferedReader buffer = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
int size = 0;
while ((line = buffer.readLine()) != null) {
String[] vals = line.trim().split(" ");
// Lazy instantiation.
if (matrix == null) {
size = vals.length;
matrix = new int[size+1][size+1];
}
for (int col = 0; col < size; col++) {
matrix[row][col] = Integer.parseInt(vals[col]);
}
row++;
}
return matrix;
}
public static void printMatrix(int[][] matrix) {
String str = "";
int size = matrix.length;
if (matrix != null) {
for (int row = 0; row < size; row++) {
str += " ";
for (int col = 0; col < size; col++) {
str += String.format("%2d", matrix[row][col]);
if (col < size - 1) {
str += " ";
}
}
if (row < size - 1) {
str += "\n";
for (int col = 0; col < size; col++) {
for (int i = 0; i < 4; i++) {
// str += " ";
}
if (col < size - 1) {
//str += "+";
}
}
str += "\n";
} else {
str += "\n";
}
}
}
System.out.println(str);
}
public static void main(String[] args)
{
int[][] matrix = null;
try {
matrix = create2DIntMatrixFromFile("sample.txt");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("The DFS Traversal for the graph is given by ");
DFS dfs = new DFS();
dfs.dfs(matrix, size);
System.out.println(" ");
printMatrix(matrix);
}
}
此输出为
The DFS Traversal for the graph is given by
0
1 5 4 6 2 3 7
0 1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0 0
0 0 0 1 0 0 1 0 0
0 0 1 0 0 0 0 1 0
1 0 0 0 0 1 0 0 0
1 1 0 0 1 0 0 0 0
0 1 1 0 0 0 0 1 0
0 0 0 1 0 0 1 0 0
0 0 0 0 0 0 0 0 0
遍历假设是
1 2 6 5 7 3 4 8
提前感谢您的帮助!