Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

螺旋矩阵 #57

Open
louzhedong opened this issue Sep 11, 2018 · 1 comment
Open

螺旋矩阵 #57

louzhedong opened this issue Sep 11, 2018 · 1 comment

Comments

@louzhedong
Copy link
Owner

习题

出处:LeetCode 算法第54题

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

思路

定义四个角四个指针,循环遍历四条边

解答

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  var result = [];
  var row = matrix.length - 1;
  var col = matrix[0].length - 1;
  var r = 0;
  var c = 0;
  while (r <= row && c <= col) {
    for (var i = r; i <= col; i++) {
      result.push(matrix[r][i]);
    }
    r++;
    for (var i = r; i <= row; i++) {
      result.push(matrix[i][col]);
    }
    col--;
    if (r <= row) {
      for (var i = col; i >= c; i--) {
        result.push(matrix[row][i]);
      }
      row--;
    }
    if (c <= col) {
      for (var i = row; i >= r; i--) {
        result.push(matrix[i][c]);
      }
      c++;
    }
  }

  return result;
};

console.log(spiralOrder([
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
]));
@FFFsssA
Copy link

FFFsssA commented May 27, 2019

if(matrix.length < 1) {return [];}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants