基于邻接矩阵的BFS广度优先搜索

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lin19931006/article/details/45062473

同前面两个小结中说道的一样


直接给出程序

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author zero
 *
 */
public class adjMatrixBFS {
	private List<Integer> visitList = new ArrayList<Integer>();
	//initial the matrix's value (1 means that two points are connected, 0 means disconnected)
	private int[][] matrix = {{1,0,1,0,1},{0,1,0,1,0},{1,1,1,0,1},{1,0,0,1,1},{1,0,0,0,0}};
	//set every point is not visited at start 
	private Boolean[] visitStatus = {false,false,false,false,false};
	
	private List<Integer> nextList = new ArrayList<Integer>();
	
	public void bfsSerach(int visitNode) {
		visitStatus[visitNode] = true;
		visitList.add(visitNode);
		for(int i=0; i<5; i++) {
			if((matrix[visitNode][i] == 1 )&&(visitStatus[i]==false)) {
				visitList.add(i);
				visitStatus[i] = true;
				nextList.add(i);
			}else {
				
			}
		}
		while(!allVisited()) {
			int num = nextList.get(nextList.size()-1);
			nextList.remove(nextList.size()-1);
			for(int i=0; i<5; i++) {
				if((matrix[num][i] == 1 )&&(visitStatus[i]==false)) {
					visitList.add(i);
					visitStatus[i] = true;
					nextList.add(i);
				}else {
					
				}
			}
		}
		
	}
	
	public Boolean allVisited() {
		Boolean result = true; 
		for(int i=0; i<5; i++) {
			if(visitStatus[i] == false) {
				result = false;
			}
		}
		return result;
	}
	
	
	public void outSortResult() {
		System.out.print("The sorted result is : ");
		for(int i=0; i<visitList.size(); i++) {
			System.out.print(visitList.get(i) + "  ");
		}
		
	}
	
	public static void main(String[] args) {
		adjMatrixBFS ambfs = new adjMatrixBFS();
		ambfs.bfsSerach(3);
		ambfs.outSortResult();
	}
}


输出的结果为:

The sorted result is : 3  0  4  2  1 


展开阅读全文

没有更多推荐了,返回首页