Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <conio.h>
- #include <malloc.h>
- int insereaza_stiva(int *stiva, int n, int vf) {
- int i;
- for (i = n - 1; i >= 0; i--)
- stiva[i + 1] = stiva[i];
- stiva[0] = vf;
- n++;
- return n;
- }
- int sterge_stiva(int *stiva, int n) {
- int i;
- for (i = 0; i < n - 1; i++)
- stiva[i] = stiva[i + 1];
- n--;
- return n;
- }
- int citeste_stiva(int *stiva, int n) {
- return stiva[0];
- }
- void depth_first(int v0, int **a, int n) {
- int *stiva, *m, i, nr_c, gasit, k;
- stiva = new int[n];
- m = new int[n];
- for (i = 0; i < n; m[i++] = 0);
- nr_c = 0;
- nr_c = insereaza_stiva(stiva, nr_c, v0);
- m[v0] = 1;
- printf_s("\n%i", v0 + 1);
- while (nr_c) {
- i = citeste_stiva(stiva, nr_c);
- gasit = 0;
- for (k = 0; (k < n) && !gasit; k++)
- if ((a[i][k] == 1) && (m[k] == 0)) {
- nr_c = insereaza_stiva(stiva, nr_c, k);
- m[k] = 1;
- printf_s("\n%i", k + 1);
- gasit = 1;
- }
- if (!gasit) nr_c = sterge_stiva(stiva, nr_c);
- }
- delete stiva;
- delete m;
- }
- int **alocare(int m, int n) {
- int **mat, i;
- mat = (int **)malloc(n*sizeof(int *));
- for (i = 0; i < n; i++)
- *(mat + i) = (int *)malloc(n*sizeof(int));
- return mat;
- }
- void dezaloca(int **mat, int m) {
- int i;
- for (i = 0; i < m; i++)
- free(*(mat + i));
- free(mat);
- }
- void main() {
- int n, v0, **a, m, i, j, vf1, vf2;
- printf_s("Nr. varfuri: "); scanf_s("%i", &n);
- a = alocare(n, n);
- for (i = 0; i < n; i++)
- for (j = 0; j <= i; j++)
- a[i][j] = a[j][i] = 0;
- printf_s("\nNr. muchii: "); scanf_s("%i", &m);
- for (i = 0; i < m; i++) {
- printf_s("Varf initial: "); scanf_s("%i", &vf1);
- printf_s("Varf final: "); scanf_s("%i", &vf2);
- a[vf1 - 1][vf2 - 1] = a[vf2 - 1][vf1 - 1] = 1;
- }
- printf_s("Varf initial pentru DF: "); scanf_s("%i", &v0);
- printf_s("Ordinea de parcurgere DF: ");
- depth_first(v0 - 1, a, n);
- dezaloca(a, n);
- _getch();
- }
Add Comment
Please, Sign In to add comment