详细见:leetcode.com/problems/spiral-matrix-ii
Java Solution: github
package leetcode;
public class P059_SpiralMatrixII {
public static void main(String[] args) {
int[][] ans = new Solution().generateMatrix(9);
tools.Utils.A_打印二维数组(ans);
}
/*
* 1 ms
* 2.83%
*/
static class Solution {
int[][] ans = null;
int count = 0;
public int[][] generateMatrix(int n) {
if (n < 1)
return new int[0][0];
ans = new int[n][n];
int eni = n >> 1;
for (int i = 0; i != eni; i ++)
fourEdge(i, n - 1 - i, n - 1 - i);
if ((n & 0x1) == 1)
ans[eni][eni] = ++count;
return ans;
}
private void fourEdge(int i, int j, int k) {
int t = 0;
for (t = i; t < k; t ++)
ans[i][t] = ++ count;
for (t = i; t < j; t ++)
ans[t][k] = ++ count;
for (t = k; t > i; t --)
ans[j][t] = ++ count;
for (t = j; t > i; t --)
ans[t][i] = ++ count;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/spiral-matrix-ii/
AC 3ms 14.29%
*/
#include <stdio.h>
#include <stdlib.h>
void shell_add(int** m, int i, int j, int* v) {
int k = 0;
for (k = i; k < j; k ++)
m[i][k] = (*v) ++;
for (k = i; k < j; k ++)
m[k][j] = (*v) ++;
for (k = j; k > i; k --)
m[j][k] = (*v) ++;
for (k = j; k > i; k --)
m[k][i] = (*v) ++;
}
int** generateMatrix(int n) {
int** m = (int**) malloc(sizeof(int*) * n);
int i = 0, j = n-1, v = 1;
for (i = 0; i < n; i ++)
m[i] = (int*) malloc(sizeof(int) * n);
i = 0;
while (i < j) {
shell_add(m, i, j, &v);
i ++;
j --;
}
if (n % 2 == 1)
m[n/2][n/2] = v;
return m;
}
int main() {
int n = 9;
int** m = generateMatrix(n);
int i = 0;
int j = 0;
for (i = 0; i < n; i ++) {
for (j = 0; j < n; j ++) {
printf("%d ", m[i][j]);
}
printf("\r\n");
}
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/spiral-matrix-ii
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月12日
@details: Solution: 62ms 20.60%
'''
class Solution(object):
def shell_add(self, ans, ai, i , j):
for k in range(i, j):
ans[i][k] = ai[0]
ai[0] += 1
for k in range(i, j):
ans[k][j] = ai[0]
ai[0] += 1
for k in range(j, i, -1):
ans[j][k] = ai[0]
ai[0] += 1
for k in range(j, i, -1):
ans[k][i] = ai[0]
ai[0] += 1
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = [[0 for i in range(n)] for j in range(n)]
i, j, ai = 0, n-1, [1]
while i < j:
self.shell_add(ans, ai, i, j)
i += 1
j -= 1
if n % 2 == 1:
ans[i][j] = ai[0]
return ans
if __name__ == "__main__":
n = 3
print(Solution().generateMatrix(n))