Un arreglo zig-zag es un arreglo cuadrado de los primeros N2 enteros, donde los nĂºmeros van ordenados de menor a mayor distribuidos en forma de zig zag a lo largo de las anti diagonales de la matriz (ver la figura).
Por ejemplo, si N es 5, el programa debe producir este arreglo:
0 1 5 6 14
2 4 7 13 15
3 8 12 16 21
9 11 17 20 22
10 18 19 23 24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# zigzag.py
#
# Copyright 2010 Javier Rovegno Campos <tatadeluxe<at>gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
def zigzag(n):
# Genera la matriz n x n rellena con 'x'
aux = [['x' for x in range(n)] for y in range(n)]
i = 0
j = 0
der = True
abajo = False
izq_abajo = False
der_arriba = False
for k in range(n**2):
aux[i][j] = k
if der:
j += 1
der = False
if i == 0:
izq_abajo = True
if i == n - 1:
der_arriba = True
continue
if abajo:
i += 1
abajo = False
if j == 0:
der_arriba = True
if j == n - 1:
izq_abajo = True
continue
if izq_abajo:
j -= 1
i += 1
if i == n - 1:
izq_abajo = False
der = True
elif j == 0:
izq_abajo = False
abajo = True
continue
if der_arriba:
j += 1
i -= 1
if j == n - 1:
der_arriba = False
abajo = True
elif i == 0:
der_arriba = False
der = True
continue
return aux
if __name__ == '__main__':
for n in range(1,15):
lnds = zigzag(n)
print 'Caso N = %s' % n
for row in lnds:
print row
|
Tags: zigzag