题意:

image.png

解题思路:

  1. 思路:O(n2)。
  2. 1. 定义四个方向:上右下左;
  3. 2. 左上角开始遍历,走到右边最大值,改变方向往下走...,遍历完所有格子后退出;
  4. 3. 我们填充时遍历一次矩阵,矩阵元素个数为 n2个,所以总时间复杂度是 O(n2);

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer $n
  4. * @return Integer[][]
  5. */
  6. function generateMatrix($n) {
  7. $top = 0;
  8. $bottom = $n - 1;
  9. $left = 0; $right = $n - 1;
  10. $num = 1;
  11. $matrix = [];
  12. while ($top <= $bottom && $left <= $right) {
  13. for ($i = $left; $i <= $right; $i++) {
  14. $matrix[$top][$i] = $num++;
  15. }
  16. $top++;
  17. for ($i = $top; $i <= $bottom; $i++) {
  18. $matrix[$i][$right] = $num++;
  19. }
  20. $right--;
  21. for ($i = $right; $i >= $left; $i--) {
  22. $matrix[$bottom][$i] = $num++;
  23. }
  24. $bottom--;
  25. for ($i = $bottom; $i >= $top; $i--) {
  26. $matrix[$i][$left] = $num++;
  27. }
  28. $left++;
  29. }
  30. foreach ($matrix as $k => $v) {
  31. ksort($v);
  32. $matrix[$k] = $v;
  33. }
  34. return $matrix;
  35. }
  36. }

GO代码实现:

  1. func generateMatrix(n int) [][]int {
  2. matrix := [][]int{}
  3. for i := 0; i < n; i++{
  4. matrix = append(matrix, make([]int, n))
  5. }
  6. size := n * n
  7. top, bottom := 0, n-1 //左右边界
  8. left, right := 0, n-1 //上下边界
  9. idx := 1
  10. for idx <= size {
  11. //向右走
  12. for i := top; i <= bottom; i++ {
  13. matrix[left][i] = idx
  14. idx++
  15. }
  16. left++ //上边界收缩
  17. //向下走
  18. for i := left; i <= right; i++ {
  19. matrix[i][bottom] = idx
  20. idx++
  21. }
  22. bottom-- //右边界收缩
  23. for i := bottom;i >= top; i-- {
  24. matrix[right][i] = idx
  25. idx++
  26. }
  27. right--
  28. for i := right; i >= left; i-- {
  29. matrix[i][top] = idx
  30. idx++
  31. }
  32. top++
  33. }
  34. return matrix
  35. }

```