Skip to content

Instantly share code, notes, and snippets.

@neiesc
Created November 21, 2010 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neiesc/709126 to your computer and use it in GitHub Desktop.
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.
#-*- 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)))
@DirleiDionisio
Copy link

Que barato encontrar uma versão do meu algoritmo tantos anos depois! 😊

@neiesc
Copy link
Author

neiesc commented May 4, 2021

Opa @DirleiDionisio faz muito tempo kkkk e vc ja citava complexidade vs simplicidade, boas praticas....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment