Created
June 13, 2025 17:53
-
-
Save thinkphp/212c4b1779677db66f72efbd9e119579 to your computer and use it in GitHub Desktop.
probleme 2 . Connected Nodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
void DFSHelper(int **graph, int node, int n, int *visited, int * connectedNodes, int *count) { | |
visited[ node ] = 1; | |
connectedNodes[ (*count)++ ] = node; | |
for(int neighbor = 0; neighbor < n; neighbor++) { | |
if(graph[node][neighbor] == 1 && !visited[neighbor]) { | |
DFSHelper(graph, neighbor, n, visited, connectedNodes, count);//recurenta | |
} | |
} | |
} | |
int **readGraph(int *size) { | |
printf("Enter the number of nodes: "); | |
scanf("%d", size); | |
int n = *size; | |
//citesti size = 5 | |
//[ptr1,ptr2,ptr3,ptr4,ptr5] | |
int **graph = (int**)malloc(n * sizeof(int*)); | |
for(int i = 0; i < n; ++i) { | |
graph[i] = (int*)malloc(n * sizeof(int)); | |
} | |
//citim matricea | |
printf("Enter the adjacency matrix (0 for no edge, 1 for edge): \n"); | |
printf("Row by row:\n"); | |
for(int i = 0; i < n; ++i) { | |
printf("Row %d: ", i + 1); | |
for(int j = 0; j < n; ++j) { | |
scanf("%d", &graph[i][j]); | |
} | |
} | |
return graph; | |
} | |
int main(int argc, char const *argv[]) { | |
int n; | |
int **graph = readGraph( &n ); | |
int startNode;//x | |
printf("Enter the node to find connections for: "); | |
scanf("%d", &startNode); | |
if(startNode < 0 || startNode >= n) { | |
printf("Invalid node number!\n"); | |
return 1; | |
} | |
int *visited = (int*)calloc(n, sizeof(int)); //vector pentru a marca nodurile vizitate | |
int *connectedNodes = (int*)malloc(n * sizeof(int));//pastram nodurile selectate | |
int count = 0; | |
// | |
DFSHelper(graph, startNode, n, visited, connectedNodes, &count); | |
printf("\nNodes connected to node %d (including itself): \n", startNode); | |
for(int i = 0; i < count; ++i) { | |
printf("%d ", connectedNodes[i]); | |
} | |
for(int i = 0; i < n; ++i) { | |
free(graph[i]); | |
} | |
free(graph); | |
free(visited); | |
free(connectedNodes); | |
return 0; | |
} | |
/* | |
malloc(Memory Allocation) | |
malloc(size_t size) | |
aloca un bloc de memorie de dimensiunea size | |
nu initializeaza memoria | |
calloc(Contiguous Allocation) | |
calloc(size_t num, size_t size) | |
aloca memorie pentru un numar de elemente , fiecare avand dimensiunea size | |
- initializeaza toti octetii cu zero 0x000 | |
Cand folosesti? | |
malloc - cand urmeaza sa scrii imediat peste toata memoria alocata | |
calloc- cand ai nevoie ca datele sa fie initializate cu 0) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment