Skip to content

Instantly share code, notes, and snippets.

@gooooloo
Created September 18, 2015 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gooooloo/c215ef0967ce0ba46442 to your computer and use it in GitHub Desktop.
Save gooooloo/c215ef0967ce0ba46442 to your computer and use it in GitHub Desktop.
package com.qidu.lin;
public class PrinterNumbers
{
/**
* 打印螺旋矩阵
0 31 30 29 28 27 26 25 24
1 32 55 54 53 52 51 50 23
2 33 56 71 70 69 68 49 22
3 34 57 72 79 78 67 48 21
4 35 58 73 80 77 66 47 20
5 36 59 74 75 76 65 46 19
6 37 60 61 62 63 64 45 18
7 38 39 40 41 42 43 44 17
8 9 10 11 12 13 14 15 16
*/
public static void main(String a[])
{
final int N = 9;
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
// 别问我,两年后再看, 我也不知道这个公式是怎么推出来的。
int round = Math.min(Math.min(row, col), Math.min(N - 1 - row, N - 1 - col));
int total = Math.max(1, 4 * N - 4 - 8 * round);
int num = (4 * round * (N - round)) + ((total + (row < col ? -1 : 1) * (row + col - 2 * round)) % total);
System.out.print(String.format("%3d", num));
System.out.print(" ");
}
System.out.print("\n");
}
}
}
@metayx
Copy link

metayx commented Jun 3, 2018

迷一样啊,老哥

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment