Created
November 21, 2010 20:43
-
-
Save neiesc/709126 to your computer and use it in GitHub Desktop.
Problema: dada uma matriz NxN, preenchê-la com números naturais em forma de espiral.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding: utf-8 -*- | |
#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 | |
#Baseado versão pascal http://pastebin.com/YRHrMSGw | |
# Blog http://maisquebomcodigo.blogspot.com/2010/05/eu-amo-meu-codigo.html | |
def alocarMatriz(largura, altura): | |
matriz = [] | |
for x in range(largura): | |
matriz.append([]) | |
for y in range(altura): matriz[x].append(None) | |
return matriz | |
def serpentearMatriz(largura, altura): | |
matriz = alocarMatriz(largura, altura) | |
totalElementos = largura * altura | |
posH = posV = nivel = contador = 1 | |
sentido = 'seDireita' | |
while contador <= totalElementos: | |
matriz[posH-1][posV-1] = contador | |
if sentido == 'seDireita': | |
if posV == altura-nivel+1: | |
posH += 1 | |
sentido = 'seAbaixo' | |
else: posV += 1 | |
elif sentido == 'seAbaixo': | |
if posH == largura-nivel+1: | |
posV -= 1 | |
sentido = 'seEsquerda' | |
else: posH += 1 | |
elif sentido == 'seEsquerda': | |
if posV == nivel: | |
posH -= 1 | |
sentido = 'seAcima' | |
else: posV -= 1 | |
elif sentido == 'seAcima': | |
if posH == nivel+1: | |
posV += 1 | |
sentido = 'seDireita' | |
nivel += 1 | |
else: posH -=1 | |
contador += 1 | |
return matriz | |
def exibirMatriz(matriz): | |
for linha in matriz: | |
for coluna in linha: | |
print("{0}\t".format(coluna), end='') | |
print() | |
print(exibirMatriz(serpentearMatriz(4,4))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Opa @DirleiDionisio faz muito tempo kkkk e vc ja citava complexidade vs simplicidade, boas praticas....