Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- { Problema: dada uma matriz NxN, preenchê-la com números naturais em forma de espiral.
- Ex: matriz 4 x 4
- 01 02 03 04
- 12 13 14 05
- 11 16 15 06
- 10 09 08 07
- }
- // by Dirlei Dionísio - 03/2010
- program Serpenteador;
- uses Dialogs, SysUtils;
- type
- TVetor = array of Integer;
- TMatriz = array of TVetor;
- TSentido = (seDireita, seAbaixo, seEsquerda, seAcima);
- procedure alocarMatriz(const largura, altura: Word; out matriz: TMatriz);
- var i: Word;
- begin
- SetLength(matriz, largura);
- for i:=0 to largura-1 do
- SetLength(matriz[i], altura);
- end;
- procedure serpentearMatriz(const largura, altura: Word; var matriz: TMatriz);
- var
- totalElementos,contador,posHorizontal,posVertical,nivel: Word;
- sentido: TSentido;
- begin
- totalElementos := largura*altura;
- posHorizontal := 1;
- posVertical := 1;
- sentido := seDireita;
- nivel := 1;
- contador := 1;
- while contador<=totalElementos do
- begin
- matriz[posHorizontal-1][posVertical-1] := contador;
- if sentido=seDireita then
- begin
- if posVertical=altura-nivel+1 then
- begin
- inc(posHorizontal,1);
- sentido := seAbaixo;
- end
- else
- inc(posVertical,1);
- end
- else if sentido=seAbaixo then
- begin
- if posHorizontal=largura-nivel+1 then
- begin
- inc(posVertical,-1);
- sentido := seEsquerda;
- end
- else
- inc(posHorizontal,1);
- end
- else if sentido=seEsquerda then
- begin
- if posVertical=nivel then
- begin
- inc(posHorizontal,-1);
- sentido := seAcima;
- end
- else
- inc(posVertical,-1);
- end
- else if sentido=seAcima then
- begin
- if posHorizontal=nivel+1 then
- begin
- inc(posVertical,1);
- sentido := seDireita;
- inc(nivel);
- end
- else
- inc(posHorizontal,-1);
- end;
- inc(contador);
- end;
- end;
- procedure exibirMatriz(const largura, altura: Word; var matriz: TMatriz);
- var
- i, j: integer;
- resultado: string;
- begin
- for i:=0 to largura-1 do
- begin
- for j:=0 to altura-1 do
- resultado := resultado + formatFloat('000000 ',matriz[i,j]);
- resultado := resultado + #13;
- end;
- showMessage(resultado);
- end;
- var
- matriz: TMatriz;
- largura, altura: Word;
- begin
- repeat
- largura := strToIntDef(inputbox('Largura', 'Qual a largura da matriz? (0 para sair)', ''),0);
- if largura<1 then break;
- altura := strToIntDef(inputbox('Altura', 'Qual a altura da matriz? (0 para sair)', ''),0);
- if altura<1 then break;
- alocarMatriz(largura,altura,matriz);
- serpentearMatriz(largura,altura,matriz);
- exibirMatriz(largura,altura,matriz);
- until false;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement