一、问题描述:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Subscribe to see which companies asked this question
二、解决思路:
画圈: 每次找到一个起点(k,k)以次画圈即可。我们注意到画圈的终止条件是 n > k * 2 理由如下:
n = 3 的时候 每次画圈的起点分别为 0 0 ; 1 1;
n = 4 的时候 每次画圈的起点分别为 0 0 ; 1 1;
n = 5 的时候 每次画圈的起点分别为 0 0 ; 1 1; 2 2;
n = 6 的时候 每次画圈的起点分别为 0 0 ; 1 1; 2 2;
n = 7 的时候 每次画圈的起点分别为 0 0 ; 1 1;2 2; 3 3;
......
三、代码:
package T12;
/**
* @author 作者 : xcy
* @version 创建时间:2016年12月28日 上午10:44:09
* 类说明
*/
public class t59 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] M = generateMatrix(3);
System.out.println("done");
}
public static int[][] generateMatrix(int n) {
int count = 1;
int[][] M = new int[n][n];
int start = 0;
int m = n;
while (n > start * 2) {
count = write(M, m, start, count);
m--;
start++;
}
return M;
}
public static int write(int[][] M, int m, int start, int count) {
int n = M.length;
int i = start;
int j = start;
// 从左到右
for (j = start; j < m; j++) {
M[i][j] = count;
count++;
}
// 从上到下
j = m - 1;
for (i = start + 1; i < m; i++) {
M[i][j] = count;
count++;
}
//从右到左
i = m - 1;
for (j = m - 2; j >= start; j--) {
M[i][j] = count;
count++;
}
//从下到上
j = n - m;
for (i = m - 2; i > start; i--) {
M[i][j] = count;
count++;
}
return count;
}
}