Python implements the print spiral matrix function, and python prints the spiral Matrix

Source: Internet
Author: User
Tags print format

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.