My code:
public class Solution {
public int[][] generateMatrix(int n) {
if (n < 0)
return null;
int[][] result = new int[n][n];
if (n == 0)
return result;
int level = n % 2 + n / 2;
int count = 1;
for (int i = 0; i < level; i++) {
for (int j = i; j < i + n - 2 * i; j++)
result[i][j] = count++;
if (n - 2 * i == 1)
return result;
for (int j = i + 1; j < i + n - 2 * i; j++)
result[j][i + n - 2 * i - 1] = count++;
for (int j = i + n - 2 * i - 2; j >= i; j--)
result[i + n - 2 * i - 1][j] = count++;
for (int j = i + n - 2 * i - 2; j > i; j--)
result[j][i] = count++;
}
return result;
}
public static void main (String[] args) {
Solution test = new Solution();
int[][] a = test.generateMatrix(4);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
}
}
My test result:
这道题目和之前的差不多。刚才因为偷懒,写了子函数没改掉,所以运行时间过长。
这道题目,就直接写在主函数的循环里面了,然后那么多for循环基本一笔写成,也基本没什么问题。脑子已经特别清楚了。虽然很累。
题目本身没有任何难度或者任何思想。。。
**
总结: Array, Math
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
private int counter = 1;
public int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
if (n <= 0)
return ret;
int scanTimes = (n + 1) / 2;
int beginRow = 0;
int beginCol = 0;
for (int i = 0; i < scanTimes; i++) {
helper(beginRow + i, beginCol + i, n - i * 2, ret);
}
return ret;
}
private void helper(int beginRow, int beginCol, int len, int[][] matrix) {
if (len == 1) {
matrix[beginRow][beginCol] = counter;
return;
}
for (int i = beginCol; i < beginCol + len; i++) {
matrix[beginRow][i] = counter;
counter++;
}
for (int i = beginRow + 1; i < beginRow + len; i++) {
matrix[i][beginCol + len - 1] = counter;
counter++;
}
for (int i = beginCol + len - 2; i >= beginCol; i--) {
matrix[beginRow + len - 1][i] = counter;
counter++;
}
for (int i = beginRow + len - 2; i > beginRow; i--) {
matrix[i][beginCol] = counter;
counter++;
}
}
}
这题目也没什么意思。。。
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int[][] generateMatrix(int n) {
if (n < 0) {
return null;
}
int[][] matrix = new int[n][n];
int rowBegin = 0;
int rowEnd = n - 1;
int colBegin = 0;
int colEnd = n - 1;
int counter = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; i++) {
matrix[rowBegin][i] = counter;
counter++;
}
rowBegin++;
for (int i = rowBegin; i <= rowEnd; i++) {
matrix[i][colEnd] = counter;
counter++;
}
colEnd--;
if (rowBegin <= rowEnd) {
for (int i = colEnd; i >= colBegin; i--) {
matrix[rowEnd][i] = counter;
counter++;
}
rowEnd--;
}
if (colBegin <= colEnd) {
for (int i = rowEnd; i>= rowBegin; i--) {
matrix[i][colBegin] = counter;
counter++;
}
colBegin++;
}
}
return matrix;
}
}
用之前 Spiral Matrix I 的做法来做,很快很方便。
Anyway, Good luck, Richardo! --- 08/11/2016