【图论】PLUS【BFS】
The graph consists of nodes and edges, simulating a set of connections, explaining how different things are connected.
图(Graph)【实现】
利用代码实现图可以有很多种,表示每个节点与邻近节点相连,散列表是最好的方式。
【散列表可以实现将键映射到值,然后就可以将节点映射到其所有邻近节点。】
【注意一点:散列表是无序的,添加键值对的顺序无关紧要】
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【队列】
首先简述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实现了完整的搜索并且打印了搜索过程
// 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回溯找到初始节点
有必要的话利用String类型变量输出最短路径
运行时间 O(V+E)【V-顶点 E-边】
让对手感动,让对手恐惧