Skip to content

Latest commit

 

History

History
109 lines (87 loc) · 2.28 KB

File metadata and controls

109 lines (87 loc) · 2.28 KB

59. Spiral Matrix II

Leetcode link

解题思路

题目要求我们给 n x n 的数组螺旋赋值

想要螺旋赋值首先就得规定好四面 “墙”,我们分别叫他们 leftrighttopbottom

我们可以把赋值的分成 4 个步骤,并在昨晚之后对墙做相应的调整:

  1. 从左到右,之后把上墙下移 ++top
  2. 从上到下,之后把右墙左移 --right
  3. 从右到左,之后把下墙上移 --bottom
  4. 从下到上,之后把左墙右移 ++left


以上四个动作为一个循环,然后不断循环缩小范围直到全部赋值完毕

C++

class Solution {
 public:
  vector<vector<int>> generateMatrix(int n) {
    vector<vector<int>> res(n, vector<int>(n));
    int left = 0, right = n - 1, top = 0, bottom = n - 1;
    int number = 1;
    // use to trace current path
    int i = 0;
    while (left <= right && top <= bottom) {
      // left to right
      while (i <= right) {
        res[top][i++] = number++;
      }
      i = ++top;

      //   top to bottom
      while (i <= bottom) {
        res[i++][right] = number++;
      }
      i = --right;

      // right to left
      while (i >= left) {
        res[bottom][i--] = number++;
      }
      i = --bottom;

      //   bottom to top
      while (i >= top) {
        res[i--][left] = number++;
      }
      i = ++left;
    }
    return res;
  }
};

Javascript

/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function(n) {
    const res = Array(n);
    for(let i = 0;i<n;i++) {
        res[i] = Array(n).fill(0);
    }
    let left = 0, right = n - 1, top = 0, bottom = n - 1;
    let number = 1;
    // use to trace current path
    let i = 0;
    while (left <= right && top <= bottom) {
      // left to right
      while (i <= right) {
        res[top][i++] = number++;
      }
      i = ++top;

      //   top to bottom
      while (i <= bottom) {
        res[i++][right] = number++;
      }
      i = --right;

      // right to left
      while (i >= left) {
        res[bottom][i--] = number++;
      }
      i = --bottom;

      //   bottom to top
      while (i >= top) {
        res[i--][left] = number++;
      }
      i = ++left;
    }
    return res;
};