Python implements the print spiral matrix function, and python prints the spiral Matrix
This article describes how to implement the print spiral Matrix Function in Python. We will share this with you for your reference. The details are as follows:
I. Problem Description
Input N, print N * N spiral Matrix
For example, N = 3, print:
1 2 3
8 9 4
7 6 5
N = 4, print:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Ii. Ideas
The conventional method is complicated to constantly judge the data boundary. You may wish to solve the number of each layer through recursion.
Iii. Code
# Coding: utf-8n = int (raw_input ('>') # initialize array arr = [0] * n for I in range (n)] # recursion solves def dfs (arr, x, y, start, n): if n <= 0: return 0 if n = 1: arr [x] [y] = start return 0 # up for I in range (n ): arr [x] [y + I] = start + = 1 # right for I in range (n-1 ): arr [x + 1 + I] [y + n-1] = start + = 1 # down for I in range (n-1 ): arr [x + n-1] [y + n-2-i] = start + = 1 # left for I in range (n-2 ): arr [x + n-2-i] [y] = start + = 1 dfs (arr, x + 1, y + 1, start, N-2) a = dfs (arr, 1, n) # format the output printl = len (str (n * n) + 1 format = ('%' + str (l) + 'D ') * nfor tmp in arr: print format % tuple (tmp)
Running result: