【圖論】PLUS【BFS】

The graph consists of nodes and edges, simulating a set of connections, explaining how different things are connected.node

圖(Graph)【實現】
利用代碼實現圖能夠有不少種,表示每一個節點與鄰近節點相連,散列表是最好的方式。
【散列表能夠實現將鍵映射到值,而後就能夠將節點映射到其全部鄰近節點。】
【注意一點:散列表是無序的,添加鍵值對的順序可有可無】web

Java中:
HashMap<String,String[]> map = new HashMap<>();
Python中:
graph = {}
Java中:
map.put("A", new String[] {"B","C"});
Python中:
graph["A"] = ["B", "C"]

如下兩圖等價,此處利用有向圖
在這裏插入圖片描述 無向圖
在這裏插入圖片描述 有向圖算法

圖(Graph)【查找】
在圖的查找算法中廣度優先算法解釋了兩個典型的問題:從A到B有路徑嗎;從A到B的最短路徑。網絡

第一個問題---->利用這種算法搜遍整個網絡。
第二個問題---->須要按添加順序進行檢查,涉及到了First In First Out【隊列】svg

首先簡述BFS實現流程函數

1.創建一個隊列,用於存儲第一步要檢查的元素
2.從隊列中彈出一個元素,檢查此元素是否爲目標元素
3.根據上一步的判斷結果,若是是則完成,若是不然將此元素的子元素添加進隊列
4.返回第二步
//startId(由console輸入的開始節點)  targetId(由console輸入的目標節點)  map(圖)
List<String> hasSearchList = new ArrayList<String>();
LinkedList<Node> queue = new LinkedList<Node>();
queue.offer(new Node(startId,null));
while(!queue.isEmpty()) {
	Node node = queue.poll();
	if(hasSearchList.contains(node.id)) {
//			Skip queried nodes and infinite loops
			continue;
	}
//  print the process of searching	
	System.out.println("judge node:"+node.id+"\n");
	if(targetId.equals(node.id)) {
		return node;
	}
	hasSearchList.add(node.id);
	if(map.get(node.id)!=null&&map.get(node.id).length>0) {
		for(String childId:map.get(node.id)) {
			queue.offer(new Node(childId,node));
		}
	}
}
return null;

以上利用Java實現了完整的搜索而且打印了搜索過程oop

// backtracking from target(the value returned by BFS)
List<Node> searchPath = new ArrayList<Node>();
searchPath.add(target);
Node node = target.parent;
while(node!=null) {
	searchPath.add(node);
	node = node.parent;
}

經過BFS函數返回值target回溯找到初始節點code

有必要的話利用String類型變量輸出最短路徑xml

運行時間 O(V+E)【V-頂點 E-邊】blog

相關文章
相關標籤/搜索