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:
這道題目和之前的差不多腮介。剛才因為偷懶肥矢,寫了子函數(shù)沒改掉,所以運行時間過長叠洗。
這道題目橄抹,就直接寫在主函數(shù)的循環(huán)里面了,然后那么多for循環(huán)基本一筆寫成惕味,也基本沒什么問題楼誓。腦子已經(jīng)特別清楚了。雖然很累名挥。
題目本身沒有任何難度或者任何思想疟羹。。。
**
總結(jié): 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