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
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 ;
}
};
这周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...