bfs找最短路(Java實現)

實現的功能:

1、建一個100個點,3000條邊的隨機圖,用鄰接鏈表保存圖的信息。(圖是隨機建成的)

2、給一個點,找出該點到其他點的最短路。

package text1;
import java.util.Random;
import java.util.Scanner;
/*實驗一:隨機生成3000條邊,100個頂點的有向圖,找出從一個點到其他點的路徑
 * 
 * 用鄰接鏈表來存圖
 * 
 * 
 * */

//定義鏈表結構
class note{
	note next = null;
	int pot;
}

public class sf1 {
	//插邊
	static void insert(note n,int p){//n是起點  p是終點
		note t = n;
		boolean b = true;
		while(t.next!=null){//去重
			t = t.next;
			if(t.pot == p){
				b = false;
				break;
			}
		}
		if(b == true){
			note newt = new note();
			newt.pot = p;
			newt.next = n.next;
			n.next = newt;
		}
	}
	
	//初始化100個頂點的有向隨機圖
	static note[] init(){
		Random r = new Random();
		
		int firp,desp;//分別代表生成隨機邊的起點和終點
		
		note[] pot = new note[100];//生成100個點
		for(int j = 0;j < 100;j ++){
			pot[j] = new note();//初始化頂點
		}
		
		for(int i = 0;i < 3000;i ++){ //生成3000條邊
			firp = r.nextInt(100); //起點
			desp = r.nextInt(100); //終點
			insert(pot[firp],desp); //邊存到鄰接鏈表中
		}
		return pot;
	}
	
	//展示鄰接鏈表
	static void display(note[] nt){
		note tem;
		for(int i = 0;i < 100;i ++){
			tem = nt[i];
			System.out.print("第"+i+"個點連接:");
			while(tem.next!=null){
				tem = tem.next;
				System.out.print(tem.pot + "-");
			}
			System.out.println("");
		}
	}
	
	//入隊
	static void push(int[] que,int end,int pot){
		que[end] = pot;
	}
	
	static int pop(int fst){
		fst = fst + 1;
		return fst;
	}
	
	public static void main(String args[]){
		note[] link;		//鄰接鏈表
		link = init();		//初始化
//		display(link);
		
		System.out.println("請隨機輸入一個0-99間的數,作爲源點");
		int first;			//源點
		Scanner sc = new Scanner(System.in);
		first = sc.nextInt();
		
		char[] color = new char[100];
		for(int i = 0;i < 100;i ++){
			color[i] = 'w';
		}
		int[] dest = new int[100];
		for(int j = 0;j < 100;j ++){
			dest[j] = -1;
		}
		
		int fst,end;
		int[] queue = new int[200];			//頂點隊列
		push(queue,0,first);
		end = 1;
		fst = 0;
		dest[queue[fst]] = 0;
		color[queue[fst]] = 'g';
		while(end > fst){
			note t = link[queue[fst]];
			while(t.next!=null){
				t = t.next;
				if(color[t.pot]=='w'){
					color[t.pot] = 'g';
					dest[t.pot] = dest[queue[fst]] + 1;
					push(queue,end,t.pot);
					end ++;
				}
			}
			color[queue[fst]] = 'b';
			fst = pop(fst);	
		}
		
		System.out.println("");
		for(int j = 0;j < 100;j ++){
			System.out.print("點"+j+"到源點的距離爲:  ");
			System.out.println(dest[j]);
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章