---
title: "回旋矩阵"
author: "vinkeychen"
date: "2010-07-25T13:08:20Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-07-28T21:09:54Z"
id: 720766
url: "https://vinkeychen.iteye.com/blog/720766"
---

这是深圳某处的一个面试题，要求打印出如下格式：

 

01. int i=5;
02. 1    2   3   4  5
03. 16 17 18 19 6
04. 15 24 25 20 7
05. 14 23 22 21 8
06. 13 12 11 10 9
07. int i=6
08. 1    2    3   4  5   6
09. 20 21 22 23 24  7
10. 19 32 33 34 25  8
11. 18 31 36 35 26  9
12. 17 30 29 28 27 10
13. 16 15 14 13 12 11

解决方案1：

01. public class SnakePrint {
02. private int orient = 0, length = 0, x = 0, y = 0;
03. // orients为顺时针90°旋转方向，前进步长为1
04. private int\[]\[] orients = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
05. private int\[]\[] arrays;
06. public SnakePrint(int length) {
07. this.length = length;
08. arrays = new int\[length]\[length];
09. }
10. // 根据当前方向返回下一个前进方向
11. private int\[] nextOrient(int\[] curOrient) {
12. int nextX = x + curOrient\[0], nextY = y + curOrient\[1];
13. // 前进方向需要顺时针旋转90°了
14. if (nextX &lt; 0 || nextX &gt;= length || nextY &lt; 0 || nextY &gt;= length
15. || arrays\[nextX]\[nextY] != 0) {
16. orient = ++orient % 4;
17. return orients\[orient];
18. }
19. return curOrient; // 不需要掉头，返回原前进方向
20. }
21. public void print() {
22. int\[] curOrient = orients\[orient]; // 初始前进方向
23. for (int i = 1; i &lt;= length * length; i++) { // 依次填充数组
24. arrays\[x]\[y] = i;
25. curOrient = nextOrient(curOrient);
26. x += curOrient\[0];
27. y += curOrient\[1];
28. }
29. for (int i = 0; i &lt; length; i++) {
30. for (int j = 0; j &lt; length; j++) {
31. System.out.printf("%4d", arrays\[i]\[j]); // 按固定4个字符宽度的格式输出
32. }
33. System.out.println();
34. }
35. }
36. public static void main(String\[] args) {
37. SnakePrint snakePrint = new SnakePrint(6);
38. snakePrint.print();
39. }
40. }

此文来自：[http://www.iteye.com/topic/545378](http://www.iteye.com/topic/545378)