program TentativaErro;
const MAXNUMVERTICES = 100;
      MAXNUMARESTAS  = 100;
type
  TipoPeso    = integer;
  TipoVertice = 0..MAXNUMVERTICES;
  TipoGrafo   = record
                  Mat: array[TipoVertice, TipoVertice] of TipoPeso;
                  NumVertices: 0..MaxNumvertices;
                  NumArestas : 0..MAXNUMARESTAS;
                end;
var
  Grafo : TipoGrafo;
  i     : integer;
  V1, V2: Tipovertice;
  Peso  : TipoPeso;

procedure FGVazio(var Grafo: TipoGrafo);
var i, j: integer;
begin
  for i := 0 to Grafo.NumVertices do
    for j := 0 to Grafo.NumVertices do
      Grafo.mat[i, j] := 0;
end;

procedure InsereAresta (var V1, V2: TipoVertice;
                        var Peso  : TipoPeso;
                        var Grafo : TipoGrafo);
begin
  Grafo.Mat[V1, V2] := peso;
end;

procedure ImprimeGrafo (var Grafo : TipoGrafo);
var i, j: integer;
begin
  write('   ');
  for i := 0 to Grafo.NumVertices-1 do write(i:3); writeln;
  for i := 0 to Grafo.NumVertices-1 do
    begin
    write(i:3);
    for j := 0 to Grafo.NumVertices-1 do
      write(Grafo.Mat[i, j]:3);
    writeln;
    end;
end; { ImprimeGrafo }

procedure Dfs (Grafo: TipoGrafo);
var Tempo, i: integer;
    d: array[0..MAXNUMVERTICES] of integer;

{  procedure Visita (k:integer);
  var j: integer;
  begin
    Tempo := Tempo + 1;  d[k] := Tempo;
    for j := 0 to Grafo.NumVertices - 1 do
      if Grafo.Mat[k,j] > 0
      then if d[j] = 0
           then begin writeln(' vertice:', j:2); Visita (j); end;
  end;
}
  procedure Visita (k:integer);
  var j: integer;
  begin
    Tempo := Tempo + 1;  d[k] := Tempo;
    for j := 0 to Grafo.NumVertices - 1 do
      if Grafo.Mat[k,j] > 0
      then if d[j] = 0
           then begin write(' Visita:', j:2); Visita (j); end;
  writeln(#10,' Desmarcando vertice:', k:2);
  Tempo := Tempo - 1;
  d[k] := 0;
  end;

begin
  Tempo := 0;
  for i := 0 to Grafo.NumVertices-1 do d[i] := 0;
  i := 0;
  writeln(' Raiz:', i:2);
  Visita (i);
end;

begin {-- Programa principal --}
{ -- NumVertices: definido antes da leitura das arestas --}
{ -- NumArestas: inicializado com zero e incrementado a --}
{ -- cada chamada de InsereAresta                       --}
  write('No. vertices:'); readln(Grafo.NumVertices);
  write('No. arestas:');  readln(Grafo.NumArestas);
  FGVazio(Grafo);
  for i := 0 to Grafo.NumArestas-1 do
    begin
    write('Insere V1 -- V2 -- Aresta:');
    readln(V1, V2, Peso);
    InsereAresta(V1, V2, Peso, Grafo); {1 chamada : G direcionado}
    InsereAresta(V2, V1, Peso, Grafo); {2 chamadas: G nao-direcionado}
    end;
  ImprimeGrafo(Grafo);
  readln;
  Dfs (Grafo);
  readln;
end.

