|
/*implementazione di un grafo mediante matrice di adiacenza*/
#include <stdlib.h>
#include <stdio.h>
#include "myLib.h"
#define BIANCO 0
#define ROSSO 1
#define VERDE 2
#define row 7
#define col 7 /* matrice quadrata */
typedef int matrice_adiacenza[row][col];
typedef matrice_adiacenza grafo;
typedef int nodo;
int BIPARTITO(grafo, nodo, int[]);
void BFS(grafo, nodo, int[]);
void DFS(grafo, nodo, int[]);
int COMP_CONNESSE(grafo, int);
void DFS_CONNESSE(grafo, nodo, int, int[]);
void adiacenza(grafo, nodo);
void stampa(matrice_adiacenza);
void reset(int[]);
int main() {
grafo g = {
/* 0 1 2 3 4 5 6 */
/*0*/{0, 1, 0, 1, 0, 0, 0},
/*1*/{1, 0, 1, 0, 1, 1, 0},
/*2*/{0, 1, 0, 1, 1, 1, 0},
/*3*/{1, 0, 1, 0, 1, 0, 0},
/*4*/{0, 1, 1, 1, 0, 0, 0},
/*5*/{0, 1, 1, 0, 0, 0, 0},
/*6*/{0, 0, 0, 0, 0, 0, 0} /* 6 componente non connessa*/
};
stampa(g);
int vivitato[row], colore[row];
printf("\n\n visita DFS partendo dal nodo 2:\n");
DFS(g,2,vivitato);
reset(vivitato);
printf("\n visita DFS partendo dal nodo 1:\n");
BFS(g,1,vivitato);
reset(colore);
if(BIPARTITO (g ,1 ,colore ))printf("\nIl grafo è bipartito");
else printf("\nIl grafo non è bipartito");
printf("\nIl grafo ha %d componenti connesse\n",COMP_CONNESSE (g ,row ));
return 0;
}
int BIPARTITO(grafo G, nodo r, int colore[]) {
nodo v, u;
int bipartito = 1;
coda Q = CREACODA();
INCODA(r, Q);
colore[r] = ROSSO;
while (!CODAVUOTA(Q) && bipartito) {
u = LEGGICODA(Q);
FUORICODA(Q);
for (v = 0; v < col; v++) {
if (G[u][v] == 1) {
if (colore[v] == BIANCO) {
colore[v] = (colore[u] == ROSSO) ? VERDE : ROSSO;
INCODA(v, Q);
} else {
if (colore[u] == colore[v]) {
bipartito = 0;
}
}
}
}
}
return bipartito;
}
int COMP_CONNESSE(grafo G, int n) {
int i;
int numComp = 0;
int comp[n];
for (i = 0; i < n; i++) {
comp[i] = 0;
}
for (i = 0; i < n; i++) {
if (comp[i] == 0) {
numComp++;
DFS_CONNESSE(G, i, numComp, comp);
}
}
return numComp;
}
void DFS_CONNESSE(grafo G, nodo u, int numComp, int comp[]) {
nodo v;
comp[u] = numComp;
for (v = 0; v < col; v++) {
if (G[u][v] == 1) {
if (comp[v] == 0) {
DFS_CONNESSE(G, v, numComp, comp);
}
}
}
}
void DFS(grafo G, nodo u, int visitati[]) {
nodo v;
visitati[u] = 1;
for (v = 0; v < col; v++) {
if (G[u][v] == 1) {
if (!visitati[v]) {
DFS(G, v, visitati);
}
}
}
}
void BFS(grafo G, nodo r, int visitati[]) {
nodo v;
nodo u;
coda Q = CREACODA();
INCODA(r, Q);
while (!CODAVUOTA(Q)) {
u = LEGGICODA(Q);
FUORICODA(Q);
visitati[u] = 1;
for (v = 0; v < col; v++) {
if (G[u][v] == 1) {
if (!visitati[v] && !APPARTCODA(v, Q)) {
INCODA(v, Q);
}
}
}
}
}
void adiacenza(grafo G, nodo u) {
nodo v;
for (v = 0; v < col; v++) {
if (G[u][v] == 1) {
printf("(%d)---->(%d)\n", u , v );
}
}
}
void stampa(matrice_adiacenza M) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (j == col - 1 )printf("\n");
}
}
}
void reset(int v[]) {
int i;
for (i = 0; i < row; i++) {
v[i] = 0;
}
}
|
|