Posted Warrior
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了相关的知识,希望对你有一定的参考价值。
01
鈥?/span>
骞垮害浼樺厛
浠€涔堟槸骞垮害浼樺厛绠楁硶锛?/strong>
璁╂垜浠墦涓瘮鏂癸細姣斿浣犳槸涓€涓灉鍐滒煡紝
閭d箞浣犲彲浠ョ户缁湪鏈嬪弸鐨勬湅鍙嬩腑瀵绘壘
鏈€鍚庣粓浜庡鎵惧埌浜嗚姃鏋滅粡閿€鍟嗐€?br>
鍏跺疄寰堢畝鍗曡繖绉嶇畻娉曢亶鍘嗕綘鐨勬暣涓汉闄呭叧绯荤綉锛岀洿鍒版壘鍒扮粡閿€鍟嗗氨鏄?span>骞垮害浼樺厛鎼滅储
骞垮害浼樺厛鎼滅储濡備笅鍥撅紝浼氬厛鍦ㄤ竴搴﹀叧绯绘壘锛岀劧鍚庢槸浜屽害鍏崇郴锛岃繖鏍峰眰灞傞€掕繘銆?/p>
骞垮害浼樺厛鎼滅储鍙互瑙e喅涓ょ被闂
绗竴绫绘槸锛氫粠A鑺傜偣瑙﹀彂鏈夊墠寰€B鑺傜偣鐨勮矾寰勪箞锛堝湪浣犵殑鍏崇郴缃戜腑鏈夎姃鏋滅粡閿€鍟嗗悧锛夛紵
绗簩绫绘槸锛氫粠A鑺傜偣瑙﹀彂鍓嶅線B鑺傜偣鐨勫摢鏉¤矾寰勬渶鐭紙鍝釜鑺掓灉缁忛攢鍟嗕笌鎴戠殑鍏崇郴鏈€杩戯級
骞垮害浼樺厛鐨勪唬鐮佸疄鐜?/strong>
渚嬪瑕佸椤剁偣A杩涜骞垮害浼樺厛閬嶅巻锛屽鎵惧埌B鐨勬渶鐭矾寰?/p>
姝ラ濡備笅锛?/strong>
棣栧厛闇€瑕佷竴涓槦鍒桻锛屾妸A鐨勪竴搴﹀ソ鍙嬫斁鍏ラ槦鍒椾腑
鍐嶉渶瑕佷竴涓泦鍚圫锛岀敤浜庡瓨鏀惧凡缁忚闂繃鐨勫厓绱狅紝閬垮厤閫犳垚寰幆璁块棶鐨勬儏鍐?/p>
瀵筈杩涜閬嶅巻锛岄槦棣栫殑鍏冪礌H涓嶅湪S涓紝骞朵笖涓嶆槸B锛屽垯閬嶅巻H鐨勪竴搴﹀ソ鍙嬫斁鍏ュ埌Q涓紝浠ユ寰幆閬嶅巻
浠g爜瀹炵幇锛?br>
public class MyGraph {
private LinkedList<Integer> adj[];
private int v; //椤剁偣鐨勪釜鏁?/span>
public MyGraph(int v) {
this.v = v;
adj = new LinkedList[v];
for (int i = 0; i < v; i++) {
adj[i] = new LinkedList<>();
}
}
public void addEdge(int s, int e) {
adj[s].add(e);
}
public void bfs(int s,int t) {
if(s == t) return;
boolean[] visited = new boolean[v];
visited[s] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
//鐢ㄤ簬璁板綍璋佽窡璋佺浉杩?/span>
int[] prev = new int[v];
for (int i = 0; i < v; ++i) {
prev[i] = -1;
}
while (queue.size()!=0){
Integer w = queue.poll();
for (int i = 0; i < adj[w].size(); i++) {
int q = adj[w].get(i);
if (!visited[q]){
prev[q] = w;
if(q==t){
print(prev, s, t);
return;
}
visited[q] = true;
queue.add(q);
}
}
}
}
private void print(int[] prev, int s, int t) { // 閫掑綊鎵撳嵃s->t鐨勮矾寰?/span>
if (prev[t] != -1 && t != s) {
print(prev, s, prev[t]);
}
System.out.print(t + " ");
}
}
骞垮害浼樺厛绠楁硶鐨勬椂闂村鏉傚害姣旇緝濂界畻锛屽氨鏄偣鐨勪釜鏁板姞涓婅竟鐨勪釜鏁?/p>
O(V+E)锛岀敱浜庤竟鐨勪釜鏁颁細杩滃ぇ浜庣偣鐨勪釜鏁帮紝鍥犳鍙互鐪嬫垚鏃堕棿澶嶆潅搴︽槸O(E)
02
鈥?/span>
娣卞害浼樺厛
娣卞害浼樺厛绠楁硶濡傚悓璧拌糠瀹紝鎴戜滑闅忔剰閫夋嫨涓€涓矓璺潵璧?/p>
褰撳彂鐜拌蛋涓嶉€氫簡锛屽啀閫€鍥炲埌涓婁竴涓矓璺彛锛岄噸鏂伴€夋嫨涓€鏉¤矾璧?/p>
鐩村埌鎵惧埌鏈€鍚庣殑鍑哄彛銆?br>
濡傚浘锛?/p>
浠g爜锛?/strong>
boolean found = false; // 鍏ㄥ眬鍙橀噺鎴栬€呯被鎴愬憳鍙橀噺
public void dfs(int s, int t) {
found = false;
boolean[] visited = new boolean[v];
int[] prev = new int[v];
for (int i = 0; i < v; ++i) {
prev[i] = -1;
}
recurDfs(s, t, visited, prev);
print(prev, s, t);
}
private void recurDfs(int w, int t, boolean[] visited, int[] prev) {
if (found == true) return;
visited[w] = true;
if (w == t) {
found = true;
return;
}
for (int i = 0; i < adj[w].size(); ++i) {
int q = adj[w].get(i);
if (!visited[q]) {
prev[q] = w;
recurDfs(q, t, visited, prev);
}
}
}
娣卞害浼樺厛姣忔潯杈硅嚦灏戜細閬嶅巻涓ゆ鍥犳澶嶆潅搴︽槸O(E)
03
鈥?/span>
鎬荤粨
骞垮害浼樺厛锛氭槸浠庤捣濮嬬偣寮€濮嬶紝鍦版寮忔悳绱紝闇€瑕佸€熷姪闃熷垪鏉ュ疄鐜般€?/p>
娣卞害浼樺厛锛氶渶瑕佸洖婧€濇兂锛屽€熷姪閫掑綊鏉ュ疄鐜般€?/p>
浜岃€呮椂闂村鏉傚害閮芥槸O(E)
以上是关于的主要内容,如果未能解决你的问题,请参考以下文章