算法分析课程作业(仅供参考)
源代码:
import java.util.LinkedList;
import java.util.Queue;
/**
* @description: Breadth first search algorithm
* @author: Qing Zhang
* @time: 09
*/
public class BFS {
/**
* @Description: Breadth first search algorithm based on queue.
* @Param: [paraGraph : Graph that need to be searched, paraNode : Node currently being traversed]
* @return: java.lang.String
*/
public static String breathFirstSearch(int[][] paraGraph, int paraNode){
Queue<Integer> tempQueue = new LinkedList<>();
boolean[] visited = new boolean[paraGraph.length];
visited[paraNode] = true;
tempQueue.add(paraNode);
String resString = ""+paraNode;
int tempNode;
while(!tempQueue.isEmpty()){
tempNode = tempQueue.poll();
for (int i = 0; i < paraGraph.length; i++) {
if(paraGraph[tempNode][i]==1 && !visited[i]){
tempQueue.add(i);
visited[i] = true;
resString += i;
}
}
}
return resString;
}
/**
* @Description: Used to test breadth-first traversal.
* @Param: []
* @return: void
*/
public static void unitTestForBFS() {
int[][] testGraph = new int[][]{
{0, 1, 0, 1, 0, 0, 1},
{1, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 1, 0, 1, 0},
{1, 0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0}
};
// Breadth-first traversal starting at each node.
for (int i = 0; i < testGraph.length; i++) {
String str = BFS.breathFirstSearch(testGraph, i);
System.out.println("Use the " + (i + 1) + "-th node as the starting position");
System.out.println(str);
}
}
public static void main(String[] args) {
BFS.unitTestForBFS();
}
}
构造数据:
运行结果:
C:\Users\Administrator\.jdks\temurin-11.0.12-1\bin\java.exe "-javaagent:E:\IntelliJ IDEA 2020.1\lib\idea_rt.jar=49850:E:\IntelliJ IDEA 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\JavaProject\JustForTest\out\production\JustForTest BFS
Use the 1-th node as the starting position
0136425
Use the 2-th node as the starting position
1043625
Use the 3-th node as the starting position
2350164
Use the 4-th node as the starting position
3021654
Use the 5-th node as the starting position
4103625
Use the 6-th node as the starting position
5230164
Use the 7-th node as the starting position
6013425
Process finished with exit code 0