O mapa tem AB e CD abertas, BC confirmada mas fechada e E isolado. Antes da atualização de BC, a BFS deA alcança apenasA,B; depois, alcançaA,B,C,D com distâncias0,1,2,3. E permanece sem caminho. A hipóteseBE é guardada fora das arestas. O programa mostra rotas/predecessores e declara separadamente que os resultados não autorizam viagem e não calculam preço ponderado. O cliente fornece GrafoLista inicializado/íntegro, até oito vértices e origem válida. BfsResultado e vetores/contadores de saída são externos, distintos e não sobrepostos ao grafo nem entre si. A BFS usa apenas arestas GR_ABERTA, em vizinhos ordenados pelo módulo, e não modifica as listas. gl_destruir libera os nós de adjacência ao fim, enquanto resultados são cópias no chamador.
alcance_demo.c
#include "bfs.h"
#include <stdio.h>
static void exibir(const char *fase, const BfsResultado *r)
{
printf("%s: init=%zu listas=%zu entradas=%zu descobertos=%d\n", fase,
r->inicializados, r->listas, r->entradas, r->quantidade);
for (int v = 0; v < r->vertices; v++) {
printf("Posto %c: distancia=%d predecessor=%d\n", 'A' + v,
r->dist[v], r->pred[v]);
}
}
static int montar(GrafoLista *g)
{
(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);
return 0;
}
return 1;
}
static void caminho(const BfsResultado *r, int destino)
{
int rota[GR_CAP];
int tamanho = 0;
int codigo = bfs_caminho(r, destino, rota, GR_CAP, &tamanho);
printf("Destino %c: r=%d", 'A' + destino, codigo);
if (codigo == BFS_OK) {
for (int i = 0; i < tamanho; i++) {
printf(" %c", 'A' + rota[i]);
}
}
putchar('\n');
}
int main(void)
{
GrafoLista g;
BfsResultado r;
if (!montar(&g)) {
puts("Falha no mapa; consulta nao iniciada.");
return 1;
}
puts("Hipotese B->E fora das arestas; relato simulado.");
if (bfs_executar(&g, 0, &r) != BFS_OK) {
gl_destruir(&g);
return 1;
}
exibir("BC fechado", &r);
caminho(&r, 3);
caminho(&r, 4);
puts("Atualizacao de disponibilidade apenas do modelo.");
(void)gl_disponivel(&g, 1, 2, 1);
if (bfs_executar(&g, 0, &r) != BFS_OK) {
gl_destruir(&g);
return 1;
}
exibir("BC disponivel", &r);
caminho(&r, 3);
caminho(&r, 4);
puts("Resultado nao autoriza viagem nem calcula preco ponderado.");
gl_destruir(&g);
return 0;
}
bfs.c
#include "bfs.h"
static void publicar(BfsResultado *destino, const BfsResultado *origem)
{
destino->vertices = origem->vertices;
destino->origem = origem->origem;
destino->quantidade = origem->quantidade;
destino->inicializados = origem->inicializados;
destino->listas = origem->listas;
destino->entradas = origem->entradas;
for (int i = 0; i < origem->vertices; i++) {
destino->dist[i] = origem->dist[i];
destino->pred[i] = origem->pred[i];
}
for (int i = 0; i < origem->quantidade; i++) {
destino->ordem[i] = origem->ordem[i];
}
}
int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida)
{
BfsResultado temp;
int fila[GR_CAP];
int inicio = 0, fim = 0;
if (g == NULL || saida == NULL || g->vertices < 0 || g->vertices > GR_CAP ||
(g->dirigido != 0 && g->dirigido != 1) ||
origem < 0 || origem >= g->vertices) {
return BFS_INVALIDO;
}
temp.vertices = g->vertices;
temp.origem = origem;
temp.quantidade = 0;
temp.inicializados = 0;
temp.listas = 0;
temp.entradas = 0;
for (int v = 0; v < g->vertices; v++) {
temp.dist[v] = -1;
temp.pred[v] = -1;
temp.inicializados++;
}
temp.dist[origem] = 0;
temp.ordem[0] = origem;
fila[fim++] = origem;
temp.quantidade = fim;
while (inicio < fim) {
int u = fila[inicio++];
const GrafoArco *p = gl_vizinhos(g, u);
temp.listas++;
while (p != NULL) {
int v = p->destino;
temp.entradas++;
if (v < 0 || v >= g->vertices || p->estado < 1 || p->estado > 2) {
return BFS_INVALIDO;
}
if (p->estado == GR_ABERTA && temp.dist[v] == -1) {
if (fim >= g->vertices || fim >= GR_CAP) {
return BFS_LIMITE;
}
temp.dist[v] = temp.dist[u] + 1;
temp.pred[v] = u;
fila[fim] = v;
temp.ordem[fim] = v;
fim++;
temp.quantidade = fim;
}
p = p->prox;
}
}
publicar(saida, &temp);
return BFS_OK;
}
int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
int capacidade, int *tamanho)
{
int reverso[GR_CAP];
int n = 0, v;
if (r == NULL || caminho == NULL || tamanho == NULL ||
r->vertices < 1 || r->vertices > GR_CAP ||
r->origem < 0 || r->origem >= r->vertices ||
r->quantidade < 1 || r->quantidade > r->vertices ||
destino < 0 || destino >= r->vertices ||
capacidade < 1 || capacidade > GR_CAP) {
return BFS_INVALIDO;
}
if (r->dist[destino] == -1) {
return BFS_SEM_CAMINHO;
}
if (r->dist[destino] < 0 || r->dist[destino] >= r->vertices) {
return BFS_INVALIDO;
}
v = destino;
for (;;) {
int pai;
if (n >= r->vertices || v < 0 || v >= r->vertices) {
return BFS_INVALIDO;
}
reverso[n++] = v;
if (v == r->origem) {
if (r->dist[v] != 0 || r->pred[v] != -1) {
return BFS_INVALIDO;
}
break;
}
if (r->dist[v] <= 0) {
return BFS_INVALIDO;
}
pai = r->pred[v];
if (pai < 0 || pai >= r->vertices || r->dist[pai] != r->dist[v] - 1) {
return BFS_INVALIDO;
}
v = pai;
}
if (n > capacidade) {
return BFS_LIMITE;
}
for (int i = 0; i < n; i++) {
caminho[i] = reverso[n - 1 - i];
}
*tamanho = n;
return BFS_OK;
}
bfs.h
#ifndef BFS_H
#define BFS_H
#include "grafos.h"
#include <stddef.h>
#define BFS_OK 1
#define BFS_SEM_CAMINHO 0
#define BFS_INVALIDO (-1)
#define BFS_LIMITE (-2)
typedef struct {
int vertices;
int origem;
int quantidade;
int dist[GR_CAP];
int pred[GR_CAP];
int ordem[GR_CAP];
size_t inicializados;
size_t listas;
size_t entradas;
} BfsResultado;
int bfs_executar(const GrafoLista *g, int origem, BfsResultado *saida);
int bfs_caminho(const BfsResultado *r, int destino, int *caminho,
int capacidade, int *tamanho);
#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
Editar e executar esta soluçãoExemplo 1 · entrada e saída esperada
Entrada padrão
(sem entrada)
Saída esperada
Hipotese B->E fora das arestas; relato simulado.
BC fechado: init=5 listas=2 entradas=3 descobertos=2
Posto A: distancia=0 predecessor=-1
Posto B: distancia=1 predecessor=0
Posto C: distancia=-1 predecessor=-1
Posto D: distancia=-1 predecessor=-1
Posto E: distancia=-1 predecessor=-1
Destino D: r=0
Destino E: r=0
Atualizacao de disponibilidade apenas do modelo.
BC disponivel: init=5 listas=4 entradas=6 descobertos=4
Posto A: distancia=0 predecessor=-1
Posto B: distancia=1 predecessor=0
Posto C: distancia=2 predecessor=1
Posto D: distancia=3 predecessor=2
Posto E: distancia=-1 predecessor=-1
Destino D: r=1 A B C D
Destino E: r=0
Resultado nao autoriza viagem nem calcula preco ponderado.
Estado de saída: 0.
Editar e testar o exemplo 1