代码
public class Main {
static ArrayList<String> vertexList;
static int[][] edges;
static int numOfEdges = 0;
static boolean[] isVisited;
public static void main(String[] args) {
String[] vertexs = {"A","B","C","D","E"};
createGraph(5);
for (int i = 0;i < vertexs.length;i++){
insertVertex(vertexs[i]);
}
insertEdge(0,1,1);
insertEdge(0,2,1);
insertEdge(1,2,1);
insertEdge(1,3,1);
insertEdge(1,4,1);
show();
bfs();
}
public static int getFirstNeighber(int cur){
for (int i = 0;i < vertexList.size();i++){
if (edges[cur][i] > 0){
if (!isVisited[i]){
return i;
}
}
}
return -1;
}
public static int getNextNerghber(int cur,int last){
for (int i = last + 1;i < vertexList.size();i++){
if (edges[cur][i] > 0){
if (!isVisited[i]){
return i;
}
}
}
return -1;
}
public static void dfs(boolean[] isVisited,int cur){
if (!isVisited[cur]){
System.out.println(vertexList.get(cur));
isVisited[cur] = true;
}
int neighberIndex = getFirstNeighber(cur);
while (neighberIndex != -1){
dfs(isVisited,neighberIndex);
neighberIndex = getNextNerghber(cur,neighberIndex);
}
}
public static void bfs(boolean[] isVisited,int cur){
LinkedList<Integer> queue = new LinkedList<>();
if (!isVisited[cur]){
System.out.println(vertexList.get(cur));
isVisited[cur] = true;
queue.addLast(cur);
}
while (!queue.isEmpty()){
cur = queue.removeFirst();
int neighberIndex = getFirstNeighber(cur);
while (neighberIndex != -1){
if (!isVisited[neighberIndex]){
System.out.println(vertexList.get(neighberIndex));
isVisited[neighberIndex] = true;
queue.addLast(neighberIndex);
}
neighberIndex = getNextNerghber(cur,neighberIndex);
}
}
}
public static void bfs(){
for (int i = 0;i < vertexList.size();i++){
bfs(isVisited,i);
}
}
public static void dfs(){
for (int i = 0;i < vertexList.size();i++){
if (!isVisited[i]){
dfs(isVisited,i);
}
}
}
public static void createGraph(int edgeNums){
vertexList = new ArrayList<String>();
edges = new int[edgeNums][edgeNums];
numOfEdges = edgeNums;
isVisited = new boolean[5];
}
public static void insertVertex(String oneVertex){
vertexList.add(oneVertex);
}
public static void insertEdge(int v1,int v2,int weight){
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
public static int getNumOfVertex(){
return vertexList.size();
}
public static int getNumOfEdges(){
return numOfEdges;
}
public static String getValueByIndex(int index){
return vertexList.get(index);
}
public static int getWeightByV1V2(int v1,int v2){
return edges[v1][v2];
}
public static void show(){
for (int[] temp: edges){
System.out.println(Arrays.toString(temp));
}
}
}
结果
[0, 1, 1, 0, 0]
[1, 0, 1, 1, 1]
[1, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
A
B
C
D
E