相比于Spiral Matrix(参见这篇文章)要简单一些,因为是方阵,所以代码简洁一些。
注意当n是奇数的时候,中心小块要单独赋值(代码21行)
代码:
1 vector<vector<int> > generateMatrix(int n) { 2 vector<vector<int> > matrix(n, vector<int>(n, 0)); 3 int len = n - 1; 4 int i = 0; 5 int j = 0; 6 int count = 1; 7 8 while (len > 0) { 9 for (int k = 0; k < len; k++) 10 matrix[i][j++] = count++; 11 for (int k = 0; k < len; k++) 12 matrix[i++][j] = count++; 13 for (int k = 0; k < len; k++) 14 matrix[i][j--] = count++; 15 for (int k = 0; k < len; k++) 16 matrix[i--][j] = count++; 17 i++; 18 j++; 19 len -= 2; 20 } 21 if (len == 0) 22 matrix[i][j] = count; 23 24 return matrix; 25 }