leetcode姣忔棩涓€棰樼郴鍒?鍏氦璺嚎
Posted 鍒樼函鑹疄鍦ㄦ槸澶偉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode姣忔棩涓€棰樼郴鍒?鍏氦璺嚎相关的知识,希望对你有一定的参考价值。
leetcode-815-鍏氦璺嚎
<!--more-->
[鍗氬閾炬帴]
鑿滒煇旂殑瀛︿範涔嬭矾
鎺橀噾棣栭〉
[棰樼洰鎻忚堪]
缁欎綘涓€涓暟缁?routes 锛岃〃绀轰竴绯诲垪鍏氦绾胯矾锛屽叾涓瘡涓?routes[i] 琛ㄧず涓€鏉″叕浜ょ嚎璺紝绗?i 杈嗗叕浜よ溅灏嗕細鍦ㄤ笂闈㈠惊鐜椹躲€?
渚嬪锛岃矾绾?routes[0] = [1, 5, 7] 琛ㄧず绗?0 杈嗗叕浜よ溅浼氫竴鐩存寜搴忓垪 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1
-> ... 杩欐牱鐨勮溅绔欒矾绾胯椹躲€?
鐜板湪浠?source 杞︾珯鍑哄彂锛堝垵濮嬫椂涓嶅湪鍏氦杞︿笂锛夛紝瑕佸墠寰€ target 杞︾珯銆?鏈熼棿浠呭彲涔樺潗鍏氦杞︺€?
姹傚嚭 鏈€灏戜箻鍧愮殑鍏氦杞︽暟閲?銆傚鏋滀笉鍙兘鍒拌揪缁堢偣杞︾珯锛岃繑鍥?-1 銆?
绀轰緥 1锛?
杈撳叆锛歳outes = [[1,2,7],[3,6,7]], source = 1, target = 6
杈撳嚭锛?
瑙i噴锛氭渶浼樼瓥鐣ユ槸鍏堜箻鍧愮涓€杈嗗叕浜よ溅鍒拌揪杞︾珯 7 , 鐒跺悗鎹箻绗簩杈嗗叕浜よ溅鍒拌溅绔?6 銆?
绀轰緥 2锛?
杈撳叆锛歳outes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
杈撳嚭锛?1
鎻愮ず锛?
1 <= routes.length <= 500.
1 <= routes[i].length <= 105
routes[i] 涓殑鎵€鏈夊€?浜掍笉鐩稿悓
sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
Related Topics 骞垮害浼樺厛鎼滅储 鏁扮粍 鍝堝笇琛?
馃憤 146 馃憥 0
[棰樼洰閾炬帴]
leetcode棰樼洰閾炬帴
[github鍦板潃]
浠g爜閾炬帴
[鎬濊矾浠嬬粛]
鎬濊矾涓€锛欱FS
- 鍒嗘瀽棰樻剰鍙互寰堝揩鐨勬兂鍒癉FS鎴栬€匓FS瑙e喅锛屽洜涓烘湰棰樺彧闇€瑕佽€冭檻閫夋嫨鐨勫叕浜よ溅绾胯矾鏁伴噺锛屼笉闇€瑕佽€冭檻绔欑偣璺嚎锛屾墍浠ョ敤骞垮害浼樺厛鍗冲彲锛屾渶鍏堥亶鍘嗗埌鐨勪竴瀹氭槸鏈€鐭殑
鑰冭檻棰樿В鐨勬椂鍊欐湁濡備笅闂锛?/p>
- 鍥犱负鏈€寮€濮?strong>涓嶅湪鍏氦杞︿笂涓斿湪1绔欏彴锛岄渶瑕佽€冭檻鏄惁routes[0]鍖呭惈1绔欏彴锛屽綋鐒惰繖鍙槸涓€涓墠鎻愭潯浠跺苟涓嶅奖鍝嶅悗缁殑瑙i杩囩▼锛屼笉澶变竴鑸€х殑鎴戜滑鍋囪绗竴鏉$嚎璺竴瀹氬寘鍚捣濮嬬珯鍙?/strong>
- 棣栧厛纭閾捐矾鍏崇郴锛屽皢鎵€鏈夌嚎璺拰绾胯矾涓殑鍖呭惈鐨勭珯鍙板瓨鍏ap锛宬ey涓虹嚎璺储寮曪紝value涓虹珯鍙扮粍鎴愮殑set
- 鐒跺悗渚濇閬嶅巻鎵€鏈塵ap锛屽綋鏈夌嚎璺寘鍚玸ource绔欏彴鐨勬椂鍊欏瓨鍏eque浣滀负BFS閬嶅巻鐨勮窡鑺傜偣
- 瀹氫箟鍙︿竴涓猰ap瀛樺叆杞Щ鍒板綋鍓嶇嚎璺殑step锛?strong>key涓哄綋鍓嶇嚎璺储寮曪紝value涓簊tep
- 鎺ヤ笅鏉ュ氨鏄父瑙勭殑BFS瑙f瀽浜?/li>
闇€瑕佹敞鎰忕殑鏄湰棰樻湁涓や釜杈圭晫鎯呭喌
- 璧峰鍜岀粓鐐瑰湪涓€鏉$嚎璺笂锛岀洿鎺ヨ繑鍥?锛?strong>铏界劧鎴戣寰楄繖涓竟鐣屽拰棰樼洰鎻忚堪鐨勫垵濮嬩笉鍦ㄥ叕浜よ溅涓婃湁鍐茬獊
- 鎵€鏈夌嚎璺病鏈夎捣鐐圭珯鍙?/strong>
public int numBusesToDestination(int[][] routes, int source, int target) {
//纭珛鎵€鏈夌嚎璺殑鍖呭惈鍏崇郴
Map<Integer, Set<Integer>> map = new HashMap<>();
for (int i = 0; i < routes.length; i++) {
Set<Integer> set = new HashSet<>();
for (int j = 0; j < routes[i].length; j++) {
set.add(routes[i][j]);
}
map.put(i, set);
}
//瀛樺偍绾胯矾绱㈠紩
Deque<Integer> deque = new LinkedList<>();
//璁板綍鍒板綋鍓嶇珯鐐圭殑绾胯矾鏁伴噺
Map<Integer, Integer> res = new HashMap<>();
//纭珛鍒濆绔欏彴
for (Integer i : map.keySet()) {
if (map.get(i).contains(source)) {
deque.add(i);
res.put(i, 1);
}
}
//corner case
if (deque.isEmpty()){
return -1;
}
if (target==source){
return 0;
}
while (!deque.isEmpty()) {
int temp = deque.poll();
int step = res.get(temp);
for (int i : map.get(temp)) {
if (i == target) {
return step;
}
for (int line : map.keySet()) {
//鍖呭惈褰撳墠鑺傜偣鐨勭嚎璺叏閮ㄥ姞鍏ュ埌deque涓户缁箍搴︿紭鍏堥亶鍘? if (res.containsKey(line)) {
continue;
}
if (map.get(line).contains(i)) {
deque.add(line);
res.put(line, step + 1);
}
}
}
}
return -1;
}
鏃堕棿澶嶆潅搴($$\\sum_{0}^{n}routes+n^2$$)
n涓虹嚎璺暟锛屾眰鍜屽叕寮忎负姣忔潯绾胯矾涓婄珯鍙扮殑鏁伴噺鍜?/strong>
以上是关于leetcode姣忔棩涓€棰樼郴鍒?鍏氦璺嚎的主要内容,如果未能解决你的问题,请参考以下文章