1. 程式人生 > >LeetCode 847. Shortest Path Visiting All Nodes

LeetCode 847. Shortest Path Visiting All Nodes

這周lc比賽最後一題比較複雜拿出來說下

An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph.

graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j are connected.

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.



Example 1:

Input: [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]
Example 2:

Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]


Note:

1 <= graph.length <= 12
0 <= graph[i].length < graph.length

1.一開始的思路 – 能否在圖中拿出一條最長的尤拉路 然後填上尤拉路中沒有的點 每次新增一個ans+2

2.tle但是正確的解,從某個點開始dfs,ans= 搜到的最到深度+(總數-搜到的最大深度)*2

class Solution {
public:
    int ans ;
    map< pair< int ,int >  ,int > dp ;
    int  dfs( int u , vector < vector< int > >  & graph , int depth,map< int , int
>
& check ){ int ans = 0 ; for( int i=0 ; i< graph[u].size() ; i++){ int v= graph[u][i] ; if( check[v] == 0 ){ check[v]++; int t = 1 + dfs( v, graph , depth+1 ,check ) ; //dp[ {u,v} ] = t -1 ; ans = max( ans , t ) ; check[v]--; } } return
ans ; } int shortestPathLength(vector<vector<int>>& graph) { int n = graph.size() ; int res = INT_MAX ; for( int i=0 ; i< n ; i++){ map< int , int > check ; ans = 0 ; check[i]++; int ans = dfs( i , graph , 0 , check ) ; int t = n -( ans + 1) ; res = min ( res, t*2 + ans ) ; } return res ; } };

在上面的程式碼中我開了沒有用到dp,想要通過記憶化搜尋去ac程式碼

思路是如果這個點搜過了,並且知道它最大的深度直接加上最大深度即可

但是有個問題那就是進來的點需要判斷是否在能搜到的最大深度的子集裡

最後這題看了discuss 得知壓縮dp通過S記錄所有點的狀態

dp[S][i] 代表著在 i 這個點的時候 ,我們搜了集合S中的狀態

如果S的二進位制是 10101代表 vertex 0,2,4 我們搜過了

如果此時的i為 1 如 dp[10101][1] 代表我們在 1 這個點時 ,搜掉10101所使用的最小代價

定義了狀態 , 需要初始化dp

對於每個vertex應該有 dp[1 << i][i] = 0 因為我們不用走就已經可以得到S這個狀態

接著是狀態轉移 和產生的代價

此處需要舉個例子

如dp[11][0] 代表此時在0處集合為11的代價,那麼他就應該滿足

dp[11][0] = min( dp[11][0] , dp[10][1] + dis[1][0] ) 
class Solution {
public:
    int dp[1<<12][12];
    int dis[12][12] ; 
    void floyd( vector< vector< int> > & graph ){
        int n = graph.size(); 
        { //floyd algorithm
        //   init floyd algorithm
        for( int i =0 ; i < n; i++){
            for( int j =0 ; j<n ; j++){
                dis[i][j] = n*n ; 
            }
        }
        for( int i  =0 ; i< n; i ++){
            dis[i][i] = 0 ; 
        }
        for( int u = 0 ; u<n ; u++){
            for( auto & v : graph[u] ){
                dis[u][v] = 1 ;
                dis[v][u] = 1; 
            }
        }
        // get the table of dis[i][j] 
            for( int k =0 ; k< n ;k++){
                for( int i =0 ; i<n ; i++){
                    for( int j=0 ; j<n ; j++){
                        if( k!=i && k!=j ){
                            dis[i][j] = min( dis[i][j] , dis[i][k] +dis[k][j] ) ; 
                        }
                    }
                }
            }
        }
    }
    int shortestPathLength(vector<vector<int>>& graph) {
        int n = graph.size() ; 
        floyd( graph ) ; 
        // init  dp array ;
        for( int i=0 ; i< n ; i++){
            for( int j=0 ; j<( 1<<n ) ; j++){
                dp[j][i] = n*n; 
            }
        }
        for( int i=0 ; i< n; i++){
            dp[1<<i][i] = 0 ; 
        }
        for( int j=1 ; j<(1<<n) ;  j++){
            for(int i=0;i<n ;i++){
                if( j &(1<<i) ) { // now the ith vertex is actually in the Set j 
                    for( int k=0 ;k<n ;k++){
                        dp[j][i] = min( dp[j][i] , dp[j^(1<<i)][k]+dis[k][i] ) ; 
                    }
                }
            }
        }
        int res = 1<< 15 ; 
        for( int i=0 ; i< n; i++){
            res = min ( res , dp[(1<<n) -1][i] ) ; 
        }
        return res; 
    }
};

此處求點對的最短路使用的是floyd演算法, 但是也可以使用n次bfs達到

相關推薦

LeetCode 847. Shortest Path Visiting All Nodes的強化學習解法

elf delta port true lse action amp ota before 這題的本意不是要考機器學習的,而且模型已知情況下,可以直接求解,不需要用MC、TD等方式。使用這個代碼,即使得到解,也不能通過本題測試。可以初步練習下調參,比如設置不同的獎勵,探索衰

leetcode 847. Shortest Path Visiting All Nodes 無向連通圖遍歷最短路徑

sel shu turn 判斷 lam 最短 額外 動態 訪問 設計最短路徑 用bfs 天然帶最短路徑 每一個狀態是 當前的階段 和已經訪問過的節點 下面是正確但是超時的代碼 class Solution: def shortestPathLength(self,

LeetCode 847. Shortest Path Visiting All Nodes

這周lc比賽最後一題比較複雜拿出來說下 An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph. graph.length = N, an

AOJ GRL_1_C: All Pairs Shortest Path (Floyd-Warshall算法求任意兩點間的最短路徑)(Bellman-Ford算法判斷負圈)

self logs var inf sel main rain test rect 題目鏈接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_C All Pairs Shortest

Aizu - GRL_1_C Shortest Path - All Pairs Shortest Path(最短路 floyd)

題目連結 題意:給出n個點m條路,求是否存在負環;不存在的輸出點之間的距離; 注意:會超int,要用long long 型; 判斷負環:floyd迴圈完一遍,如果存在dis[i][i]<0,證明存在負環;     #include <iostr

LeetCode-All Nodes Distance K in Binary Tree

一、Description 題目描述:給定一個二叉樹,一個target結點,一個K,找出所有離target結點的距離為K的所有結點,返回一個list。 Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5

LeetCode-863. All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K. Return a list of the values of all 

LeetCode All Nodes Distance K in Binary Tree

給定一個二叉樹(具有根結點 root), 一個目標結點 target ,和一個整數值 K 。 返回到目標結點 target 距離為 K 的所有結點的值的列表。 答案可以以任何順序返回。 示

[leetcode]863. All Nodes Distance K in Binary Tree

[leetcode]863. All Nodes Distance K in Binary Tree Analysis normal day—— [每天刷題並不難0.0] We are given a binary tree (with root node r

[LeetCode] Shortest Distance from All Buildings 建築物的最短距離

You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and

864. Shortest Path to Get All Keys

We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b",

所有節點對之間的最短路問題(All Pair Shortest Path)--《演算法導論》

給定一個有向圖求出裡面所有節點對之間的最短路徑。 問題的詳細描述見Wikipedia:https://en.wikipedia.org/wiki/Shortest_path_problem。 介紹兩個演算法O(V3)的Floyd演算法和O(V2lgV+VE)

Leetcode 863. All Nodes Distance K in Binary Tree

解法:便利所有除了目標節點分支的節點,標記他們的爸爸和自己是左是右。然後從目標節點向外便利。/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNo

LeetCode 64. Minimum Path Sum 20170515

tco path sum obj .com 最小 ima minimum type elif Given a m x n grid filled with non-negative numbers, find a path from top left to bottom r

leetcode鏈表--15、everse-nodes-in-k-group(按照k值進行k個結點的逆序)

逆序 ever alter 解題思路 for chang 所有 node weight 題目描述 Given a linked list, reverse the nodes of a linked list k at a time and return its mod

leetcode鏈表--16、swap-nodes-in-pairs(成對交換鏈表結點)

ive push 返回 pre head 交換 while const int 題目描述 Given a linked list, swap every two adjacent nodes and return its head. For example, Given

[Leetcode] Substring with concatenation of all words 串聯所有單詞的子串

一聲 count 博客 oot 之間 back 空格 理解 是不是 You are given a string, S, and a list of words, L, that are all of the same length. Find all starting i

LeetCode 63. Unique Path II(所有不同路徑之二)

con etc 關鍵點 lan 題目 lis total middle blog Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many un

LeetCode 64. Minimum Path Sum(最小和的路徑)

turn paths [0 solution 返回 資料 lan 需要 i++ Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right wh

[GeeksForGeeks] Populate inorder successor for all nodes in a binary search tree

stack iter pro get root following sin ice nod Given a binary search tree with the following tree node definition. next points to a node‘s