Python/PHP数字螺旋矩阵的程序代码
矩阵不管在php或python中它只是一种算法了,我们要做的就是利用我们所学的程序来实现这种算法即可达到我们的需求了,下面来看它们的实现方法。
什么是螺旋矩阵? 螺旋矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大,如此循环。下图就是一个螺旋矩阵的示例: 郑晓在这里分别使用了Python和PHP来实现了数字的螺旋矩阵。其中的PHP版本写成了函数,更加灵活的对矩阵进行控制。写Python时由于是第一次写,有些生疏,分别用了两种方法来实现。。。下面上代码吧: Python螺旋矩阵的第一版(比较难以理解?!): #coding:gbk L = 6 #矩阵大小 result = [[0]*L for n in range(L)] row =0 #初始行 从左上角开始 col = 0 #初始列 从左上角开始 value = 1#初始值 direction = 'r' #初始方向 向右 circle = 1 #初始圈数 第一圈 while True: #向右走 if direction == 'r': result[row][col] = value if col>=L-circle: direction = 'd' continue col += 1 #向下走 if direction =='d': result[row][col] = value if row >= L-circle: direction = 'l' continue row += 1 #向左走 if direction == 'l': result[row][col] = value if col <= circle -1: direction = 'u' continue col -= 1 #向上走 if direction == 'u': result[row][col] = value if row-1 <= circle: direction = 'r' circle += 1 #continue row -= 1 value += 1 if value > L * L : break for R in result: for c in R: print "%3d" % (c) , print raw_input()
接下来是Python螺旋矩阵的第二版,其中使用了迭代器控制方向,代码量明显减少,而且更容易理解了。多次使用不同的起点生成的矩阵时,你会发现有个地方写的有点儿“问题”,找到问题了没有?
#coding:gbk import itertools #参数:矩阵宽(w)、高(h)、起始横坐标、起始纵坐标 def print_matrix(w, h, x = 0, y = 0): #方向移动时的操作 op = [(1,0), (-1,0), (0,-1), (0,1)] #迭代器可无限迭代列表 每次要换方向时就next() direction = itertools.cycle(op) #根据行列生成所有坐标 result = {(xx,yy):None for xx in range(w) for yy in range(h)} result[(x,y)] = 1 _x, _y = direction.next() i = 1 flag = 0 while True: new_x = x + _x new_y = y + _y if (new_x, new_y) in result and result[(new_x, new_y)] is None: i = i + 1 result[(new_x, new_y)] = i x = new_x y = new_y flag = 0 else: _x, _y = direction.next() flag = flag + 1 if flag>4: break #打印结果 for y in range(h): for x in range(w): print "%3d" % (result[(x,y)]), print #调用示例 print_matrix(6,6,5,0) raw_input()
下面是PHP版的螺旋矩阵,思路和上面的Python是一样的(其实我是照着写的…)。
/* * * @param $w : 宽 * @param $h : 高 * @param $s : 起始数字 * @param $x, $y : 起始位置坐标 只能从四顶点开始 * @param $r :方向 默认顺时间 false为逆时针 * @author : 郑晓 * php5.6.11 * 这是一个螺旋矩阵的PHP版本,由于之前在python下写过,有了一些经验,所以在php中也使用了SPL的一个迭代器,用于换向。算法编写时是使用的过程式,后来又改为了函数,加入了一些自定义参数,方便调用(然并卵)。输出中使用的是制表和换行符,请在浏览器源代码中查看运行结果。 */ function print_matrix($w, $h, $s=1, $l=1, $x=0, $y=0, $r=true) { $R = array(array(1,0), array(0,1), array(-1,0), array(0,-1)); !$r && $R = array_reverse($R); $iterator = new InfiniteIterator(new ArrayIterator($R)); //创建一个无限迭代器 $iterator->rewind(); //指针指向第一元素 list($_x, $_y) = $iterator->current(); $result = []; $result[$x][$y] = $s; for($i = $s+1; $i < $s+$w * $h; $i++) { $new_x = $x + $_x; $new_y = $y + $_y; if(0<= $new_x && 0<= $new_y && $new_x < $w && $new_y < $h && !isset($result[$new_x][$new_y])) { $result[$new_x][$new_y] = $i; $x = $new_x; $y = $new_y; } else { $iterator->next(); list($_x, $_y) = $iterator->current(); $i--; } } //以下是打印矩阵结构 for($i=0; $i< $h; $i++) { for($j=0; $j< $w; $j++) { echo $result[$j][$i], "\t"; } echo "\n"; } } //调用示例测试 print_matrix(5, 5); echo "\n"; print_matrix(7, 4); echo "\n"; print_matrix(5, 5, 1, 4, 0); echo "\n"; print_matrix(5, 5, 10, 0, 4, false); echo "\n";
下面是依次的运行结果:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode
