ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

LeetCode //C - 1192. Critical Connections in a Network

LeetCode //C - 1192. Critical Connections in a Network 1192. Critical Connections in a NetworkThere are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network wherec o n n e c t i o n s [ i ] [ a i , b i ] connections[i] [a_i, b_i]connections[i][ai​,bi​]represents a connection between serversa i a_iai​andb i b_ibi​. Any server can reach other servers directly or indirectly through the network.A critical connection is a connection that, if removed, will make some servers unable to reach some other server.Return all critical connections in the network in any order.Example 1:Input:n 4, connections [[0,1],[1,2],[2,0],[1,3]]Output:[[1,3]]Explanation:[[3,1]] is also accepted.Example 2:Input:n 2, connections [[0,1]]Output:[[0,1]]Constraints:2 n 10 5 2 n 10^52n105n − 1 c o n n e c t i o n s . l e n g t h 10 5 n - 1 connections.length 10^5n−1connections.length1050 a i , b i n − 1 0 a_i, b_i n - 10ai​,bi​n−1a i ! b i a_i ! b_iai​!bi​There are no repeated connections.From: LeetCodeLink: 1192. Critical Connections in a NetworkSolution:Ideas:use Tarjan DFS; edge u-v is critical when low[v] disc[u].Code:#includestdlib.h#includestring.hint*head,*to,*nextEdge;intedgeCnt;int*disc,*low;inttimeCnt;int**ans;intansCnt;intmin(inta,intb){returnab?a:b;}voidaddEdge(intu,intv){to[edgeCnt]v;nextEdge[edgeCnt]head[u];head[u]edgeCnt;}voiddfs(intu,intparentEdge){disc[u]low[u]timeCnt;for(intehead[u];e!-1;enextEdge[e]){intvto[e];if((e^1)parentEdge)continue;if(disc[v]0){dfs(v,e);low[u]min(low[u],low[v]);if(low[v]disc[u]){ans[ansCnt]malloc(sizeof(int)*2);ans[ansCnt][0]u;ans[ansCnt][1]v;ansCnt;}}else{low[u]min(low[u],disc[v]);}}}int**criticalConnections(intn,int**connections,intconnectionsSize,int*connectionsColSize,int*returnSize,int**returnColumnSizes){headmalloc(sizeof(int)*n);tomalloc(sizeof(int)*connectionsSize*2);nextEdgemalloc(sizeof(int)*connectionsSize*2);disccalloc(n,sizeof(int));lowmalloc(sizeof(int)*n);for(inti0;in;i)head[i]-1;edgeCnt0;for(inti0;iconnectionsSize;i){intuconnections[i][0];intvconnections[i][1];addEdge(u,v);addEdge(v,u);}ansmalloc(sizeof(int*)*connectionsSize);ansCnt0;timeCnt0;dfs(0,-1);*returnSizeansCnt;*returnColumnSizesmalloc(sizeof(int)*ansCnt);for(inti0;iansCnt;i){(*returnColumnSizes)[i]2;}free(head);free(to);free(nextEdge);free(disc);free(low);returnans;}
返回列表