12 exercícios · Livro III

Até o Fim de Cada Caminho

Dicas e resoluções dos exercícios do capítulo 13 de Os Caminhos de Valdora.

Os enunciados preservam os identificadores da primeira edição. Abra cada resposta depois de tentar.

L3-C13-E01

Compreensão#

Fora do RPG: uma busca de arquivos aprofunda cada subpasta antes de voltar. Relacione esse comportamento à DFS e explique a necessidade de controlar visitas se houver ligações cíclicas.

Ver uma dica

Aprofundar antes de passar ao irmão corresponde à busca em profundidade.

Ver resolução comentada

DFS visita uma subpasta e seus descendentes antes de retornar para a próxima alternativa. Se atalhos ou ligações formarem ciclos, registre identidades já visitadas antes de recursar, para não repetirA→B→A indefinidamente. Um nome de arquivo isolado pode não bastar como identidade, pois nomes iguais podem existir em locais diferentes.

L3-C13-E02

Previsão#

No grafo não dirigido AB,AC,BD,CE, com origem A e vizinhos em ordem alfabética, qual sequência de descobertas resulta da DFS recursiva?

Ver uma dica

Cada vizinho novo é explorado por inteiro antes de continuar no atual.

Ver resolução comentada

A sequência de descobertas é A,B,D,C,E. DeA vai aB; deB vai aD; retorna aB eA; só então entra emC e depoisE. A ordem depende da origem e da convenção alfabética dos vizinhos.

L3-C13-E03

Compreensão#

Explique por que uma DFS iniciada em um único vértice não encontra necessariamente todos os componentes. Distinga esse fato de uma falha de implementação.

Ver uma dica

Uma busca por origem visita apenas o que está alcançável a partir dela.

Ver resolução comentada

Uma DFS iniciada emA não pode descobrir um vértice isolado ou outra componente sem ligação comA. Isso atende o contrato de alcance por origem e não é defeito. Para obter todas as componentes de um grafo não dirigido, percorra todos os vértices e inicie uma nova DFS para cada ainda não visitado. Em grafos dirigidos, essa rotina simples não define componentes fortemente conexos.

L3-C13-E04

Teste de mesa#

Fora do RPG: no grafo de salas AB,BC,CA,CD e vértice E isolado, faça DFS recursiva a partir de A. Registre descoberta, chamada recursiva, retorno e arestas que encontram visitados.

Ver uma dica

Marque um vértice ao entrar, antes de examinar seus vizinhos.

Ver resolução comentada

DescobreA e chamaB. EmB, a arestaBA encontraA visitado; chamaC. EmC, CA eCB encontram visitados; chamaD. EmD, DC encontraC visitado; retornaD→C→B→A. Ao continuar os vizinhos deA, AC encontraC já visitado. Descobertas A,B,C,D; retornos D,C,B,A; E permanece não visitado. Arestas para o pai também são vistas, pois o grafo é não dirigido.

L3-C13-E05

Teste de mesa#

Faça DFS completa sobre A,B,C,D,E no grafo de E04, iniciando nova busca quando encontrar um vértice não visitado. Liste os componentes e a raiz de cada busca.

Ver uma dica

Uma varredura externa inicia outra raiz quando o estado ainda é não visitado.

Ver resolução comentada

Na ordemA,B,C,D,E, a busca iniciada emA forma a componente {A,B,C,D}, raizA. Os próximosB,C,D já estão marcados e não reiniciam. E forma a componente {E}, raizE. Total duas componentes, incluindo o vértice isolado.

L3-C13-E06

Teste de mesa#

No grafo de E02, simule DFS iterativa que marca ao retirar, ignora retirados já visitados e empilha vizinhos não visitados em ordem alfabética inversa. Registre pilha e descobertas e compare com a versão recursiva.

Ver uma dica

Empilhar em ordem inversa faz o menor vizinho ficar no topo.

Ver resolução comentada

Pilha escrita base→topo. Inicial[A]. RetiraA, descobreA e empilhaC,B: [C,B]. RetiraB, descobreB e empilhaD: [C,D]. RetiraD, descobreD: [C]. RetiraC, descobreC e empilhaE: [E]. RetiraE, descobreE: []. Descobertas A,B,D,C,E, iguais à recursiva nesse grafo e sob essas regras. Em grafos com caminhos que convergem, podem existir pendências duplicadas que precisam ser descartadas ao retirar.

L3-C13-E07

Depuração#

O pseudocódigo visitar(v); para cada vizinho u: dfs(u); é executado no triângulo AB,BC,CA. Mostre a repetição infinita e acrescente estado de visita no momento apropriado.

Ver uma dica

A visita precisa mudar o estado antes de criar chamadas para os vizinhos.

Ver resolução comentada

Sem guarda, A chamaB, que chamaA, que chamaB novamente, antes mesmo de concluir o triângulo. Ao entrar, marque visitado[v]=1; para cada vizinhou, chame dfs(u) somente se ainda não visitado. Também é possível começar a função retornando se v já foi visitado. Limpar o estado antes de uma nova execução é responsabilidade explícita da operação.

L3-C13-E08

Depuração#

Um relatório chama o primeiro caminho produzido por DFS de caminho com menor número de arestas. Use AB,BD,DE,AC,CE, origem A e destino E, vizinhos alfabéticos, para comparar o caminho encontrado com uma alternativa menor.

Ver uma dica

A primeira rota profunda pode ser mais longa que uma alternativa rasa.

Ver resolução comentada

Com vizinhos alfabéticos, a DFS pode descobrirE por A–B–D–E, três arestas. Existe A–C–E, com duas. Logo o relatório correto é “caminho encontrado pela DFS”, não “menor número de arestas”. Para esse objetivo sem pesos, use a garantia da BFS, sem inferir custo monetário ou autorização.

L3-C13-E09

Implementação#

Fora do RPG: implemente DFS recursiva que devolva ordem de descoberta para a rede de E04. Garanta visita única por execução e permita reiniciar a busca com estados limpos.

Ver uma dica

O estado de visita deve começar limpo em cada execução, não ficar global.

Ver resolução comentada

dfs_recursiva inicializa seu resultado temporário com grupo/pred−1, marca ao entrar e só publica após sucesso. O grafo é inicializado, íntegro e finito, com até oito vértices, sem laços/duplicatas; a implementação percorre só arestas abertas. O resultado é objeto externo sem alias com o grafo. As listas pertencem ao grafo e são destruídas pelo cliente após as consultas. O cliente monta E04 e executa duas vezes a partir deA: ambas descobremA,B,C,D uma vez, e E continua não alcançado. O reinício não reaproveita marcações antigas e não altera as ligações.

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

dfs.h

#ifndef DFS_H
#define DFS_H
#include "grafos.h"
#include <stddef.h>

#define DFS_OK 1
#define DFS_INVALIDO (-1)
#define DFS_LIMITE (-2)
#define DFS_PILHA (1 + GR_CAP * (GR_CAP - 1))

typedef struct {
    int vertices, quantidade, retornos, componentes;
    int grupo[GR_CAP], pred[GR_CAP];
    int ordem[GR_CAP], fim[GR_CAP];
    size_t inicializados, listas, entradas;
    size_t empilhados, descartados, pico;
} DfsResultado;

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_componentes(const GrafoLista *g, DfsResultado *saida);
#endif

dfs.c

#include "dfs.h"

typedef struct {
    int vertice, pai;
} Pendente;

static int valido(const GrafoLista *g)
{
    return g != NULL && g->vertices >= 0 && g->vertices <= GR_CAP &&
           (g->dirigido == 0 || g->dirigido == 1);
}

static void iniciar(DfsResultado *r, int vertices)
{
    r->vertices = vertices;
    r->quantidade = r->retornos = r->componentes = 0;
    r->inicializados = r->listas = r->entradas = 0;
    r->empilhados = r->descartados = r->pico = 0;
    for (int v = 0; v < vertices; v++) {
        r->grupo[v] = r->pred[v] = -1;
        r->inicializados++;
    }
}

static void publicar(DfsResultado *d, const DfsResultado *s)
{
    d->vertices = s->vertices;
    d->quantidade = s->quantidade;
    d->retornos = s->retornos;
    d->componentes = s->componentes;
    d->inicializados = s->inicializados;
    d->listas = s->listas;
    d->entradas = s->entradas;
    d->empilhados = s->empilhados;
    d->descartados = s->descartados;
    d->pico = s->pico;
    for (int v = 0; v < s->vertices; v++) {
        d->grupo[v] = s->grupo[v];
        d->pred[v] = s->pred[v];
    }
    for (int i = 0; i < s->quantidade; i++) {
        d->ordem[i] = s->ordem[i];
    }
    for (int i = 0; i < s->retornos; i++) {
        d->fim[i] = s->fim[i];
    }
}

static int visitar(const GrafoLista *g, int u, int pai, int grupo,
                   DfsResultado *r)
{
    const GrafoArco *p;
    r->grupo[u] = grupo;
    r->pred[u] = pai;
    r->ordem[r->quantidade++] = u;
    r->listas++;
    p = gl_vizinhos(g, u);
    while (p != NULL) {
        int v = p->destino;
        r->entradas++;
        if (v < 0 || v >= g->vertices ||
            (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
            return DFS_INVALIDO;
        }
        if (p->estado == GR_ABERTA && r->grupo[v] == -1) {
            int codigo = visitar(g, v, u, grupo, r);
            if (codigo != DFS_OK) {
                return codigo;
            }
        }
        p = p->prox;
    }
    r->fim[r->retornos++] = u;
    return DFS_OK;
}

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    int codigo;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    codigo = visitar(g, origem, -1, 0, &temp);
    if (codigo == DFS_OK) {
        publicar(saida, &temp);
    }
    return codigo;
}

int dfs_componentes(const GrafoLista *g, DfsResultado *saida)
{
    DfsResultado temp;
    if (!valido(g) || saida == NULL || g->dirigido != 0) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    for (int v = 0; v < g->vertices; v++) {
        if (temp.grupo[v] == -1) {
            int codigo = visitar(g, v, -1, temp.componentes, &temp);
            if (codigo != DFS_OK) {
                return codigo;
            }
            temp.componentes++;
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    Pendente pilha[DFS_PILHA];
    int topo = 0;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    pilha[topo++] = (Pendente){origem, -1};
    temp.empilhados = temp.pico = 1;
    while (topo > 0) {
        Pendente atual = pilha[--topo];
        int u = atual.vertice;
        int vizinhos[GR_CAP], n = 0;
        const GrafoArco *p;
        if (temp.grupo[u] != -1) {
            temp.descartados++;
            continue;
        }
        temp.grupo[u] = 0;
        temp.pred[u] = atual.pai;
        temp.ordem[temp.quantidade++] = u;
        temp.listas++;
        p = gl_vizinhos(g, u);
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices ||
                (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
                return DFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.grupo[v] == -1) {
                if (n >= GR_CAP) {
                    return DFS_LIMITE;
                }
                vizinhos[n++] = v;
            }
            p = p->prox;
        }
        for (int i = n; i > 0; i--) {
            if (topo >= DFS_PILHA) {
                return DFS_LIMITE;
            }
            pilha[topo++] = (Pendente){vizinhos[i - 1], u};
            temp.empilhados++;
            if ((size_t)topo > temp.pico) {
                temp.pico = (size_t)topo;
            }
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

main.c

#include <stdio.h>
#include "dfs.h"
int montar(GrafoLista *g){if(gl_iniciar(g,5,0)!=GR_OK)return 0;int a[4][2]={{0,1},{1,2},{2,0},{2,3}};for(int i=0;i<4;i++)if(gl_adicionar(g,a[i][0],a[i][1],1)!=GR_OK){gl_destruir(g);return 0;}return 1;}
int main(void){GrafoLista g;if(!montar(&g))return 1;for(int rodada=1;rodada<=2;rodada++){DfsResultado r;if(dfs_recursiva(&g,0,&r)!=DFS_OK){gl_destruir(&g);return 1;}printf("Rodada%d:",rodada);for(int i=0;i<r.quantidade;i++)printf(" %c",'A'+r.ordem[i]);printf("; Egrupo%d\n",r.grupo[4]);}gl_destruir(&g);return 0;}
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

(sem entrada)

Saída esperada

Rodada1: A B C D; Egrupo-1
Rodada2: A B C D; Egrupo-1

Estado de saída: 0.

Editar e testar o exemplo 1

L3-C13-E10

Implementação#

Implemente contagem de componentes em grafo não dirigido. Teste grafo vazio, quatro vértices sem arestas e o grafo de E04.

Ver uma dica

Conte novas raízes, incluindo a raiz de cada isolado.

Ver resolução comentada

dfs_componentes exige grafo não dirigido e percorre todos os vértices, começando nova visita quando grupo ainda é−1. Vazio tem zero componentes; quatro vértices sem arestas têm quatro; E04 tem duas. O grafo é inicializado, íntegro e finito, com até oito vértices, sem laços/duplicatas; a implementação percorre só arestas abertas. O resultado é objeto externo sem alias com o grafo. As listas pertencem ao grafo e são destruídas pelo cliente após as consultas. A rotina recusa um modelo dirigido, para não dar nome de componentes conexos a uma propriedade diferente.

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

dfs.h

#ifndef DFS_H
#define DFS_H
#include "grafos.h"
#include <stddef.h>

#define DFS_OK 1
#define DFS_INVALIDO (-1)
#define DFS_LIMITE (-2)
#define DFS_PILHA (1 + GR_CAP * (GR_CAP - 1))

typedef struct {
    int vertices, quantidade, retornos, componentes;
    int grupo[GR_CAP], pred[GR_CAP];
    int ordem[GR_CAP], fim[GR_CAP];
    size_t inicializados, listas, entradas;
    size_t empilhados, descartados, pico;
} DfsResultado;

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_componentes(const GrafoLista *g, DfsResultado *saida);
#endif

dfs.c

#include "dfs.h"

typedef struct {
    int vertice, pai;
} Pendente;

static int valido(const GrafoLista *g)
{
    return g != NULL && g->vertices >= 0 && g->vertices <= GR_CAP &&
           (g->dirigido == 0 || g->dirigido == 1);
}

static void iniciar(DfsResultado *r, int vertices)
{
    r->vertices = vertices;
    r->quantidade = r->retornos = r->componentes = 0;
    r->inicializados = r->listas = r->entradas = 0;
    r->empilhados = r->descartados = r->pico = 0;
    for (int v = 0; v < vertices; v++) {
        r->grupo[v] = r->pred[v] = -1;
        r->inicializados++;
    }
}

static void publicar(DfsResultado *d, const DfsResultado *s)
{
    d->vertices = s->vertices;
    d->quantidade = s->quantidade;
    d->retornos = s->retornos;
    d->componentes = s->componentes;
    d->inicializados = s->inicializados;
    d->listas = s->listas;
    d->entradas = s->entradas;
    d->empilhados = s->empilhados;
    d->descartados = s->descartados;
    d->pico = s->pico;
    for (int v = 0; v < s->vertices; v++) {
        d->grupo[v] = s->grupo[v];
        d->pred[v] = s->pred[v];
    }
    for (int i = 0; i < s->quantidade; i++) {
        d->ordem[i] = s->ordem[i];
    }
    for (int i = 0; i < s->retornos; i++) {
        d->fim[i] = s->fim[i];
    }
}

static int visitar(const GrafoLista *g, int u, int pai, int grupo,
                   DfsResultado *r)
{
    const GrafoArco *p;
    r->grupo[u] = grupo;
    r->pred[u] = pai;
    r->ordem[r->quantidade++] = u;
    r->listas++;
    p = gl_vizinhos(g, u);
    while (p != NULL) {
        int v = p->destino;
        r->entradas++;
        if (v < 0 || v >= g->vertices ||
            (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
            return DFS_INVALIDO;
        }
        if (p->estado == GR_ABERTA && r->grupo[v] == -1) {
            int codigo = visitar(g, v, u, grupo, r);
            if (codigo != DFS_OK) {
                return codigo;
            }
        }
        p = p->prox;
    }
    r->fim[r->retornos++] = u;
    return DFS_OK;
}

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    int codigo;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    codigo = visitar(g, origem, -1, 0, &temp);
    if (codigo == DFS_OK) {
        publicar(saida, &temp);
    }
    return codigo;
}

int dfs_componentes(const GrafoLista *g, DfsResultado *saida)
{
    DfsResultado temp;
    if (!valido(g) || saida == NULL || g->dirigido != 0) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    for (int v = 0; v < g->vertices; v++) {
        if (temp.grupo[v] == -1) {
            int codigo = visitar(g, v, -1, temp.componentes, &temp);
            if (codigo != DFS_OK) {
                return codigo;
            }
            temp.componentes++;
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    Pendente pilha[DFS_PILHA];
    int topo = 0;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    pilha[topo++] = (Pendente){origem, -1};
    temp.empilhados = temp.pico = 1;
    while (topo > 0) {
        Pendente atual = pilha[--topo];
        int u = atual.vertice;
        int vizinhos[GR_CAP], n = 0;
        const GrafoArco *p;
        if (temp.grupo[u] != -1) {
            temp.descartados++;
            continue;
        }
        temp.grupo[u] = 0;
        temp.pred[u] = atual.pai;
        temp.ordem[temp.quantidade++] = u;
        temp.listas++;
        p = gl_vizinhos(g, u);
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices ||
                (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
                return DFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.grupo[v] == -1) {
                if (n >= GR_CAP) {
                    return DFS_LIMITE;
                }
                vizinhos[n++] = v;
            }
            p = p->prox;
        }
        for (int i = n; i > 0; i--) {
            if (topo >= DFS_PILHA) {
                return DFS_LIMITE;
            }
            pilha[topo++] = (Pendente){vizinhos[i - 1], u};
            temp.empilhados++;
            if ((size_t)topo > temp.pico) {
                temp.pico = (size_t)topo;
            }
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

main.c

#include <stdio.h>
#include "dfs.h"
int montar(GrafoLista *g){if(gl_iniciar(g,5,0)!=GR_OK)return 0;int a[4][2]={{0,1},{1,2},{2,0},{2,3}};for(int i=0;i<4;i++)if(gl_adicionar(g,a[i][0],a[i][1],1)!=GR_OK){gl_destruir(g);return 0;}return 1;}
int main(void){GrafoLista g;DfsResultado r;if(gl_iniciar(&g,0,0)!=GR_OK)return 1;if(dfs_componentes(&g,&r)!=DFS_OK)return 1;printf("Vazio:%d\n",r.componentes);gl_destruir(&g);if(gl_iniciar(&g,4,0)!=GR_OK)return 1;if(dfs_componentes(&g,&r)!=DFS_OK){gl_destruir(&g);return 1;}printf("Quatro isolados:%d\n",r.componentes);gl_destruir(&g);if(!montar(&g))return 1;if(dfs_componentes(&g,&r)!=DFS_OK){gl_destruir(&g);return 1;}printf("E04:%d\n",r.componentes);gl_destruir(&g);return 0;}
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

(sem entrada)

Saída esperada

Vazio:0
Quatro isolados:4
E04:2

Estado de saída: 0.

Editar e testar o exemplo 1

L3-C13-E11

Implementação#

Implemente DFS iterativa com pilha. Documente quando marca visitados e em qual ordem empilha vizinhos; compare os conjuntos alcançados com a versão recursiva, sem exigir ordens iguais quando as regras diferirem.

Ver uma dica

A marca ao retirar permite duplicatas pendentes, mas cada vértice é descoberto uma única vez.

Ver resolução comentada

A implementação iterativa marca quando retira, ignora retirados já marcados e empilha vizinhos não visitados em ordem alfabética inversa. Um limite de pilha explícito protege o domínio de até oito vértices. O grafo é inicializado, íntegro e finito, com até oito vértices, sem laços/duplicatas; a implementação percorre só arestas abertas. O resultado é objeto externo sem alias com o grafo. As listas pertencem ao grafo e são destruídas pelo cliente após as consultas. No triângulo de E04, uma pendência duplicada é descartada. O teste compara os conjuntos de alcançados da recursiva e da iterativa, sem transformar coincidência de ordem em obrigação geral.

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

dfs.h

#ifndef DFS_H
#define DFS_H
#include "grafos.h"
#include <stddef.h>

#define DFS_OK 1
#define DFS_INVALIDO (-1)
#define DFS_LIMITE (-2)
#define DFS_PILHA (1 + GR_CAP * (GR_CAP - 1))

typedef struct {
    int vertices, quantidade, retornos, componentes;
    int grupo[GR_CAP], pred[GR_CAP];
    int ordem[GR_CAP], fim[GR_CAP];
    size_t inicializados, listas, entradas;
    size_t empilhados, descartados, pico;
} DfsResultado;

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_componentes(const GrafoLista *g, DfsResultado *saida);
#endif

dfs.c

#include "dfs.h"

typedef struct {
    int vertice, pai;
} Pendente;

static int valido(const GrafoLista *g)
{
    return g != NULL && g->vertices >= 0 && g->vertices <= GR_CAP &&
           (g->dirigido == 0 || g->dirigido == 1);
}

static void iniciar(DfsResultado *r, int vertices)
{
    r->vertices = vertices;
    r->quantidade = r->retornos = r->componentes = 0;
    r->inicializados = r->listas = r->entradas = 0;
    r->empilhados = r->descartados = r->pico = 0;
    for (int v = 0; v < vertices; v++) {
        r->grupo[v] = r->pred[v] = -1;
        r->inicializados++;
    }
}

static void publicar(DfsResultado *d, const DfsResultado *s)
{
    d->vertices = s->vertices;
    d->quantidade = s->quantidade;
    d->retornos = s->retornos;
    d->componentes = s->componentes;
    d->inicializados = s->inicializados;
    d->listas = s->listas;
    d->entradas = s->entradas;
    d->empilhados = s->empilhados;
    d->descartados = s->descartados;
    d->pico = s->pico;
    for (int v = 0; v < s->vertices; v++) {
        d->grupo[v] = s->grupo[v];
        d->pred[v] = s->pred[v];
    }
    for (int i = 0; i < s->quantidade; i++) {
        d->ordem[i] = s->ordem[i];
    }
    for (int i = 0; i < s->retornos; i++) {
        d->fim[i] = s->fim[i];
    }
}

static int visitar(const GrafoLista *g, int u, int pai, int grupo,
                   DfsResultado *r)
{
    const GrafoArco *p;
    r->grupo[u] = grupo;
    r->pred[u] = pai;
    r->ordem[r->quantidade++] = u;
    r->listas++;
    p = gl_vizinhos(g, u);
    while (p != NULL) {
        int v = p->destino;
        r->entradas++;
        if (v < 0 || v >= g->vertices ||
            (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
            return DFS_INVALIDO;
        }
        if (p->estado == GR_ABERTA && r->grupo[v] == -1) {
            int codigo = visitar(g, v, u, grupo, r);
            if (codigo != DFS_OK) {
                return codigo;
            }
        }
        p = p->prox;
    }
    r->fim[r->retornos++] = u;
    return DFS_OK;
}

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    int codigo;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    codigo = visitar(g, origem, -1, 0, &temp);
    if (codigo == DFS_OK) {
        publicar(saida, &temp);
    }
    return codigo;
}

int dfs_componentes(const GrafoLista *g, DfsResultado *saida)
{
    DfsResultado temp;
    if (!valido(g) || saida == NULL || g->dirigido != 0) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    for (int v = 0; v < g->vertices; v++) {
        if (temp.grupo[v] == -1) {
            int codigo = visitar(g, v, -1, temp.componentes, &temp);
            if (codigo != DFS_OK) {
                return codigo;
            }
            temp.componentes++;
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    Pendente pilha[DFS_PILHA];
    int topo = 0;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    pilha[topo++] = (Pendente){origem, -1};
    temp.empilhados = temp.pico = 1;
    while (topo > 0) {
        Pendente atual = pilha[--topo];
        int u = atual.vertice;
        int vizinhos[GR_CAP], n = 0;
        const GrafoArco *p;
        if (temp.grupo[u] != -1) {
            temp.descartados++;
            continue;
        }
        temp.grupo[u] = 0;
        temp.pred[u] = atual.pai;
        temp.ordem[temp.quantidade++] = u;
        temp.listas++;
        p = gl_vizinhos(g, u);
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices ||
                (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
                return DFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.grupo[v] == -1) {
                if (n >= GR_CAP) {
                    return DFS_LIMITE;
                }
                vizinhos[n++] = v;
            }
            p = p->prox;
        }
        for (int i = n; i > 0; i--) {
            if (topo >= DFS_PILHA) {
                return DFS_LIMITE;
            }
            pilha[topo++] = (Pendente){vizinhos[i - 1], u};
            temp.empilhados++;
            if ((size_t)topo > temp.pico) {
                temp.pico = (size_t)topo;
            }
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

main.c

#include <stdio.h>
#include "dfs.h"
int montar(GrafoLista *g){if(gl_iniciar(g,5,0)!=GR_OK)return 0;int a[4][2]={{0,1},{1,2},{2,0},{2,3}};for(int i=0;i<4;i++)if(gl_adicionar(g,a[i][0],a[i][1],1)!=GR_OK){gl_destruir(g);return 0;}return 1;}
int main(void){GrafoLista g;DfsResultado a,b;if(!montar(&g))return 1;if(dfs_recursiva(&g,0,&a)!=DFS_OK||dfs_iterativa(&g,0,&b)!=DFS_OK){gl_destruir(&g);return 1;}int iguais=1;for(int v=0;v<g.vertices;v++)if((a.grupo[v]!=-1)!=(b.grupo[v]!=-1))iguais=0;printf("Recursiva%d iterativa%d mesmos_alcancados%d descartados%zu\n",a.quantidade,b.quantidade,iguais,b.descartados);gl_destruir(&g);return iguais?0:1;}
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

(sem entrada)

Saída esperada

Recursiva4 iterativa4 mesmos_alcancados1 descartados1

Estado de saída: 0.

Editar e testar o exemplo 1

L3-C13-E12

Missão#

Gere relatório dos setores conectados e isolados no mapa regional. Permita inspecionar uma ramificação por DFS, registre retornos e não apresente o percurso como rota mínima.

Ver uma dica

Relate componentes do modelo disponível sem afirmar isolamento do mundo real.

Ver resolução comentada

O projeto regional usa AB e CD abertas, BC confirmada mas fechada e E isolado. Antes de abrir BC no modelo, componentes{A,B},{C,D},{E}; depois,{A,B,C,D},{E}. A inspeção por DFS deA registra descobertas, predecessores e retornos recursivos; E permanece em componente própria. O grafo é inicializado, íntegro e finito, com até oito vértices, sem laços/duplicatas; a implementação percorre só arestas abertas. O resultado é objeto externo sem alias com o grafo. As listas pertencem ao grafo e são destruídas pelo cliente após as consultas. O programa declara que não fornece rota mínima nem autorização física. Alterar disponibilidade na representação não significa confirmar uma informação de campo ou uma decisão coletiva.

dfs.c

#include "dfs.h"

typedef struct {
    int vertice, pai;
} Pendente;

static int valido(const GrafoLista *g)
{
    return g != NULL && g->vertices >= 0 && g->vertices <= GR_CAP &&
           (g->dirigido == 0 || g->dirigido == 1);
}

static void iniciar(DfsResultado *r, int vertices)
{
    r->vertices = vertices;
    r->quantidade = r->retornos = r->componentes = 0;
    r->inicializados = r->listas = r->entradas = 0;
    r->empilhados = r->descartados = r->pico = 0;
    for (int v = 0; v < vertices; v++) {
        r->grupo[v] = r->pred[v] = -1;
        r->inicializados++;
    }
}

static void publicar(DfsResultado *d, const DfsResultado *s)
{
    d->vertices = s->vertices;
    d->quantidade = s->quantidade;
    d->retornos = s->retornos;
    d->componentes = s->componentes;
    d->inicializados = s->inicializados;
    d->listas = s->listas;
    d->entradas = s->entradas;
    d->empilhados = s->empilhados;
    d->descartados = s->descartados;
    d->pico = s->pico;
    for (int v = 0; v < s->vertices; v++) {
        d->grupo[v] = s->grupo[v];
        d->pred[v] = s->pred[v];
    }
    for (int i = 0; i < s->quantidade; i++) {
        d->ordem[i] = s->ordem[i];
    }
    for (int i = 0; i < s->retornos; i++) {
        d->fim[i] = s->fim[i];
    }
}

static int visitar(const GrafoLista *g, int u, int pai, int grupo,
                   DfsResultado *r)
{
    const GrafoArco *p;
    r->grupo[u] = grupo;
    r->pred[u] = pai;
    r->ordem[r->quantidade++] = u;
    r->listas++;
    p = gl_vizinhos(g, u);
    while (p != NULL) {
        int v = p->destino;
        r->entradas++;
        if (v < 0 || v >= g->vertices ||
            (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
            return DFS_INVALIDO;
        }
        if (p->estado == GR_ABERTA && r->grupo[v] == -1) {
            int codigo = visitar(g, v, u, grupo, r);
            if (codigo != DFS_OK) {
                return codigo;
            }
        }
        p = p->prox;
    }
    r->fim[r->retornos++] = u;
    return DFS_OK;
}

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    int codigo;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    codigo = visitar(g, origem, -1, 0, &temp);
    if (codigo == DFS_OK) {
        publicar(saida, &temp);
    }
    return codigo;
}

int dfs_componentes(const GrafoLista *g, DfsResultado *saida)
{
    DfsResultado temp;
    if (!valido(g) || saida == NULL || g->dirigido != 0) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    for (int v = 0; v < g->vertices; v++) {
        if (temp.grupo[v] == -1) {
            int codigo = visitar(g, v, -1, temp.componentes, &temp);
            if (codigo != DFS_OK) {
                return codigo;
            }
            temp.componentes++;
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida)
{
    DfsResultado temp;
    Pendente pilha[DFS_PILHA];
    int topo = 0;
    if (!valido(g) || saida == NULL || origem < 0 || origem >= g->vertices) {
        return DFS_INVALIDO;
    }
    iniciar(&temp, g->vertices);
    temp.componentes = 1;
    pilha[topo++] = (Pendente){origem, -1};
    temp.empilhados = temp.pico = 1;
    while (topo > 0) {
        Pendente atual = pilha[--topo];
        int u = atual.vertice;
        int vizinhos[GR_CAP], n = 0;
        const GrafoArco *p;
        if (temp.grupo[u] != -1) {
            temp.descartados++;
            continue;
        }
        temp.grupo[u] = 0;
        temp.pred[u] = atual.pai;
        temp.ordem[temp.quantidade++] = u;
        temp.listas++;
        p = gl_vizinhos(g, u);
        while (p != NULL) {
            int v = p->destino;
            temp.entradas++;
            if (v < 0 || v >= g->vertices ||
                (p->estado != GR_FECHADA && p->estado != GR_ABERTA)) {
                return DFS_INVALIDO;
            }
            if (p->estado == GR_ABERTA && temp.grupo[v] == -1) {
                if (n >= GR_CAP) {
                    return DFS_LIMITE;
                }
                vizinhos[n++] = v;
            }
            p = p->prox;
        }
        for (int i = n; i > 0; i--) {
            if (topo >= DFS_PILHA) {
                return DFS_LIMITE;
            }
            pilha[topo++] = (Pendente){vizinhos[i - 1], u};
            temp.empilhados++;
            if ((size_t)topo > temp.pico) {
                temp.pico = (size_t)topo;
            }
        }
    }
    publicar(saida, &temp);
    return DFS_OK;
}

dfs.h

#ifndef DFS_H
#define DFS_H
#include "grafos.h"
#include <stddef.h>

#define DFS_OK 1
#define DFS_INVALIDO (-1)
#define DFS_LIMITE (-2)
#define DFS_PILHA (1 + GR_CAP * (GR_CAP - 1))

typedef struct {
    int vertices, quantidade, retornos, componentes;
    int grupo[GR_CAP], pred[GR_CAP];
    int ordem[GR_CAP], fim[GR_CAP];
    size_t inicializados, listas, entradas;
    size_t empilhados, descartados, pico;
} DfsResultado;

int dfs_recursiva(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_iterativa(const GrafoLista *g, int origem, DfsResultado *saida);
int dfs_componentes(const GrafoLista *g, DfsResultado *saida);
#endif

grafos.c

#include "grafos.h"
#include <stddef.h>
#include <stdlib.h>

static int configuracao(int n, int dirigido)
{
    return n >= 0 && n <= GR_CAP && (dirigido == 0 || dirigido == 1);
}

static int indice(int n, int v)
{
    return v >= 0 && v < n;
}

static int forma_m(const GrafoMatriz *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

static int forma_l(const GrafoLista *g)
{
    return g != NULL && configuracao(g->vertices, g->dirigido);
}

int gm_iniciar(GrafoMatriz *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            g->aresta[u][v] = 0;
        }
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

int gm_estado(const GrafoMatriz *g, int u, int v)
{
    if (!forma_m(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    return g->aresta[u][v];
}

int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel)
{
    if (gm_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (g->aresta[u][v] != 0) {
        return GR_DUPLICADA;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_remover(GrafoMatriz *g, int u, int v)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = 0;
    if (!g->dirigido) {
        g->aresta[v][u] = 0;
    }
    return GR_OK;
}

int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel)
{
    int estado = gm_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    g->aresta[u][v] = disponivel ? GR_ABERTA : GR_FECHADA;
    if (!g->dirigido) {
        g->aresta[v][u] = g->aresta[u][v];
    }
    return GR_OK;
}

int gm_conferir(const GrafoMatriz *g)
{
    if (!forma_m(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        for (int v = 0; v < GR_CAP; v++) {
            int e = g->aresta[u][v];
            if (e < 0 || e > 2 || (u == v && e != 0) ||
                ((u >= g->vertices || v >= g->vertices) && e != 0) ||
                (!g->dirigido && e != g->aresta[v][u])) {
                return 0;
            }
        }
    }
    return 1;
}

int gl_iniciar(GrafoLista *g, int n, int dirigido)
{
    if (g == NULL || !configuracao(n, dirigido)) {
        return GR_INVALIDO;
    }
    for (int u = 0; u < GR_CAP; u++) {
        g->cabeca[u] = NULL;
    }
    g->vertices = n;
    g->dirigido = dirigido;
    return GR_OK;
}

static GrafoArco **posicao(GrafoLista *g, int u, int v)
{
    GrafoArco **p = &g->cabeca[u];
    while (*p != NULL && (*p)->destino < v) {
        p = &(*p)->prox;
    }
    return p;
}

const GrafoArco *gl_vizinhos(const GrafoLista *g, int u)
{
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return NULL;
    }
    return g->cabeca[u];
}

int gl_estado(const GrafoLista *g, int u, int v)
{
    const GrafoArco *p;
    if (!forma_l(g) || !indice(g->vertices, u) || !indice(g->vertices, v)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL && p->destino < v) {
        p = p->prox;
    }
    return p != NULL && p->destino == v ? p->estado : GR_AUSENTE;
}

int gl_adicionar(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado;
    if (gl_estado(g, u, v) < 0 || u == v ||
        (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    pu = posicao(g, u, v);
    if (*pu != NULL && (*pu)->destino == v) {
        return GR_DUPLICADA;
    }
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv != NULL && (*pv)->destino == u) {
            return GR_INVALIDO;
        }
    }
    a = malloc(sizeof *a);
    if (a == NULL) {
        return GR_MEMORIA;
    }
    if (!g->dirigido) {
        b = malloc(sizeof *b);
        if (b == NULL) {
            free(a);
            return GR_MEMORIA;
        }
    }
    estado = disponivel ? GR_ABERTA : GR_FECHADA;
    a->destino = v;
    a->estado = estado;
    a->prox = *pu;
    if (b != NULL) {
        b->destino = u;
        b->estado = estado;
        b->prox = *pv;
    }
    *pu = a;
    if (b != NULL) {
        *pv = b;
    }
    return GR_OK;
}

int gl_remover(GrafoLista *g, int u, int v)
{
    GrafoArco **pu, **pv = NULL;
    GrafoArco *a, *b = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || u == v) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
        b = *pv;
    }
    a = *pu;
    *pu = a->prox;
    if (b != NULL) {
        *pv = b->prox;
    }
    free(a);
    if (b != NULL) {
        free(b);
    }
    return GR_OK;
}

int gl_disponivel(GrafoLista *g, int u, int v, int disponivel)
{
    GrafoArco **pu, **pv = NULL;
    int estado = gl_estado(g, u, v);
    if (estado < 0 || (disponivel != 0 && disponivel != 1)) {
        return GR_INVALIDO;
    }
    if (estado == 0) {
        return GR_AUSENTE;
    }
    pu = posicao(g, u, v);
    if (!g->dirigido) {
        pv = posicao(g, v, u);
        if (*pv == NULL || (*pv)->destino != u) {
            return GR_INVALIDO;
        }
    }
    (*pu)->estado = disponivel ? GR_ABERTA : GR_FECHADA;
    if (pv != NULL) {
        (*pv)->estado = (*pu)->estado;
    }
    return GR_OK;
}

int gl_grau(const GrafoLista *g, int u)
{
    const GrafoArco *p;
    int grau = 0;
    if (!forma_l(g) || !indice(g->vertices, u)) {
        return GR_INVALIDO;
    }
    p = g->cabeca[u];
    while (p != NULL) {
        grau++;
        p = p->prox;
    }
    return grau;
}

int gl_conferir(const GrafoLista *g)
{
    int visto[GR_CAP][GR_CAP] = {{0}};
    int total = 0;
    if (!forma_l(g)) {
        return 0;
    }
    for (int u = 0; u < GR_CAP; u++) {
        const GrafoArco *p = g->cabeca[u];
        int anterior = -1;
        if (u >= g->vertices && p != NULL) {
            return 0;
        }
        while (p != NULL) {
            if (total >= GR_CAP * (GR_CAP - 1) ||
                !indice(g->vertices, p->destino) || p->destino == u ||
                p->destino <= anterior || p->estado < 1 || p->estado > 2) {
                return 0;
            }
            visto[u][p->destino] = p->estado;
            anterior = p->destino;
            total++;
            p = p->prox;
        }
    }
    if (!g->dirigido) {
        for (int u = 0; u < g->vertices; u++) {
            for (int v = 0; v < g->vertices; v++) {
                if (visto[u][v] != visto[v][u]) {
                    return 0;
                }
            }
        }
    }
    return 1;
}

void gl_destruir(GrafoLista *g)
{
    if (g == NULL) {
        return;
    }
    for (int u = 0; u < GR_CAP; u++) {
        while (g->cabeca[u] != NULL) {
            GrafoArco *p = g->cabeca[u];
            g->cabeca[u] = p->prox;
            free(p);
        }
    }
    g->vertices = 0;
    g->dirigido = 0;
}

int gl_converter(const GrafoMatriz *origem, GrafoLista *destino)
{
    GrafoLista temporario;
    if (!gm_conferir(origem) || !forma_l(destino)) {
        return GR_INVALIDO;
    }
    (void)gl_iniciar(&temporario, origem->vertices, origem->dirigido);
    for (int u = 0; u < origem->vertices; u++) {
        for (int v = 0; v < origem->vertices; v++) {
            int estado = origem->aresta[u][v];
            if (estado != 0 && (origem->dirigido || u < v)) {
                int r = gl_adicionar(&temporario, u, v, estado == GR_ABERTA);
                if (r != GR_OK) {
                    gl_destruir(&temporario);
                    return r;
                }
            }
        }
    }
    gl_destruir(destino);
    *destino = temporario;
    (void)gl_iniciar(&temporario, 0, 0);
    return GR_OK;
}

grafos.h

#ifndef GRAFOS_H
#define GRAFOS_H

#define GR_CAP 8
#define GR_OK 1
#define GR_AUSENTE 0
#define GR_INVALIDO (-1)
#define GR_DUPLICADA (-2)
#define GR_MEMORIA (-3)
#define GR_FECHADA 1
#define GR_ABERTA 2

typedef struct {
    int vertices;
    int dirigido;
    int aresta[GR_CAP][GR_CAP];
} GrafoMatriz;

typedef struct GrafoArco {
    int destino;
    int estado;
    struct GrafoArco *prox;
} GrafoArco;

typedef struct {
    int vertices;
    int dirigido;
    GrafoArco *cabeca[GR_CAP];
} GrafoLista;

int gm_iniciar(GrafoMatriz *g, int vertices, int dirigido);
int gm_estado(const GrafoMatriz *g, int u, int v);
int gm_adicionar(GrafoMatriz *g, int u, int v, int disponivel);
int gm_remover(GrafoMatriz *g, int u, int v);
int gm_disponivel(GrafoMatriz *g, int u, int v, int disponivel);
int gm_conferir(const GrafoMatriz *g);
int gl_iniciar(GrafoLista *g, int vertices, int dirigido);
int gl_estado(const GrafoLista *g, int u, int v);
int gl_adicionar(GrafoLista *g, int u, int v, int disponivel);
int gl_remover(GrafoLista *g, int u, int v);
int gl_disponivel(GrafoLista *g, int u, int v, int disponivel);
const GrafoArco *gl_vizinhos(const GrafoLista *g, int u);
int gl_grau(const GrafoLista *g, int u);
int gl_conferir(const GrafoLista *g);
int gl_converter(const GrafoMatriz *origem, GrafoLista *destino);
void gl_destruir(GrafoLista *g);
#endif

setores_demo.c

#include "dfs.h"
#include <stdio.h>

static void relatorio(const char *fase, const DfsResultado *r)
{
    printf("%s: componentes=%d init=%zu listas=%zu entradas=%zu\n",
           fase, r->componentes, r->inicializados, r->listas, r->entradas);
    for (int v = 0; v < r->vertices; v++) {
        printf("Setor %c grupo=%d pai=%d\n", 'A' + v, r->grupo[v], r->pred[v]);
    }
    printf("Descobertas:");
    for (int i = 0; i < r->quantidade; i++) {
        printf(" %c", 'A' + r->ordem[i]);
    }
    printf("\nRetornos:");
    for (int i = 0; i < r->retornos; i++) {
        printf(" %c", 'A' + r->fim[i]);
    }
    putchar('\n');
}

int main(void)
{
    GrafoLista g;
    DfsResultado r;
    (void)gl_iniciar(&g, 5, 0);
    if (gl_adicionar(&g, 0, 1, 1) != GR_OK ||
        gl_adicionar(&g, 1, 2, 0) != GR_OK ||
        gl_adicionar(&g, 2, 3, 1) != GR_OK) {
        gl_destruir(&g);
        puts("Falha no mapa; relatorio nao iniciado.");
        return 1;
    }
    puts("Modelo nao dirigido; so entradas abertas conectam setores.");
    if (dfs_componentes(&g, &r) != DFS_OK) {
        gl_destruir(&g);
        return 1;
    }
    relatorio("BC fechado", &r);
    if (dfs_recursiva(&g, 0, &r) != DFS_OK) {
        gl_destruir(&g);
        return 1;
    }
    printf("Inspecao de A: R=%d; C_grupo=%d E_grupo=%d\n",
           r.quantidade, r.grupo[2], r.grupo[4]);
    puts("Mudanca apenas no modelo; nenhuma autorizacao fisica.");
    (void)gl_disponivel(&g, 1, 2, 1);
    if (dfs_componentes(&g, &r) != DFS_OK) {
        gl_destruir(&g);
        return 1;
    }
    relatorio("BC aberto", &r);
    puts("DFS nao fornece rota minima nem prova isolamento no mundo.");
    gl_destruir(&g);
    return 0;
}
Editar e executar esta solução
Exemplo 1 · entrada e saída esperada

Entrada padrão

(sem entrada)

Saída esperada

Modelo nao dirigido; so entradas abertas conectam setores.
BC fechado: componentes=3 init=5 listas=5 entradas=6
Setor A grupo=0 pai=-1
Setor B grupo=0 pai=0
Setor C grupo=1 pai=-1
Setor D grupo=1 pai=2
Setor E grupo=2 pai=-1
Descobertas: A B C D E
Retornos: B A D C E
Inspecao de A: R=2; C_grupo=-1 E_grupo=-1
Mudanca apenas no modelo; nenhuma autorizacao fisica.
BC aberto: componentes=2 init=5 listas=5 entradas=6
Setor A grupo=0 pai=-1
Setor B grupo=0 pai=0
Setor C grupo=0 pai=1
Setor D grupo=0 pai=2
Setor E grupo=1 pai=-1
Descobertas: A B C D E
Retornos: D C B A E
DFS nao fornece rota minima nem prova isolamento no mundo.

Estado de saída: 0.

Editar e testar o exemplo 1

Complemento web criado com IA sob direção do autor e revisto por agentes. Os programas usam os recursos disponíveis até este capítulo. A licença dos códigos e do apoio é MIT; o texto dos livros e as ilustrações mantêm direitos próprios.

Galeria