componenti connesse #6
Replies: 6 comments 3 replies
-
L'idea è quella che c'è un nodo immaginario pub fn find_components(graph: &[Vec<usize>]) -> Vec<usize> {
let mut components = vec![0; graph.len()];
let mut component = 1;
for x in 0..graph.len() {
if components[x] == 0 {
dfs_components(graph, x, &mut components, component);
component += 1;
}
}
components
}
fn dfs_components(graph: &[Vec<usize>], x: usize, components: &mut Vec<usize>, component: usize) {
components[x] = component;
for &y in &graph[x] {
if components[y] == 0 {
dfs_components(graph, y, components, component)
}
}
} |
Beta Was this translation helpful? Give feedback.
-
Comp(Graph G)
} Dfs_rec_comp(Graph g , vert x , int[n] comp , int index) comp[x]=index
} |
Beta Was this translation helpful? Give feedback.
-
Ciao a tutti. Ho fatto questo codice Python al volo. Ho un po' un dubbio per quel che concerne il costo computazionale. def trova_componenti(graph):
visit = set()
res = []
def dfs(x):
visit.add(x)
if x<len(graph):
for i in graph[x]:
if i not in visit:
res[-1].add(x)
res[-1].add(i)
dfs(i)
for x in range(len(graph)):
if x not in visit:
res.append(set())
dfs(x)
return res
if __name__ == "__main__":
graph = [[1], [2, 0], [3, 1, 4], [2], [2], [6], [5]]
print(trova_componenti(graph))
|
Beta Was this translation helpful? Give feedback.
-
def dfs(graph, x, conect,cc, componet):
conect[x] = cc
componet.append(x)
for y in graph[x]:
if conect[y] == 0:
componet = dfs(graph, y, conect,cc, componet)
return componet
def found_conected(graph):
conect = len(graph)*[0]
output = []
cc = 1
for i in range(len(graph)):
componet = []
if conect[i] == 0:
output.append(dfs(graph, i, conect, cc, componet))
cc+=1
return output |
Beta Was this translation helpful? Give feedback.
-
Itero su tutti i vertici
|
Beta Was this translation helpful? Give feedback.
-
def componenti_connesse(G)
comp = [0,...,0]
C = 0
for v in V(G){
if comp[v] == 0{
assegna_componente(vis, comp, v, C++)
}
}
return comp
def assegna_componente(vis, comp, v, C)
comp[v] = C
for w in v.adiacente(){
assegna_componente(vis, comp, w, C)
} |
Beta Was this translation helpful? Give feedback.
-
Dato un grafo non diretto$G = (V, E)$ scrivere lo pseudocodice di un algoritmo che trova le componenti connesse del grafo in $O(|V| + |E|)$
a
di lunghezzaa[v] = i
indica che il verticev
sta nell'i
-esima componente connessaBeta Was this translation helpful? Give feedback.
All reactions