xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 螺旋矩阵 II 算法题解 All In One

LeetCode 螺旋矩阵 II 算法题解 All In One

js / ts 生成螺旋矩阵

螺旋矩阵原理 图解

动态赋值 arr[i]

  // 动态更新 index
  let i = 0;
  while (left <= right && top <= bottom && i < arr.length) {
    for (let column = left; column <= right; column++) {
      matrix[top][column] = arr[i];
      i++;
    }
    for (let row = top + 1; row <= bottom; row++) {
      matrix[row][right] = arr[i];
      i++;
    }
    if (left < right && top < bottom) {
        for (let column = right - 1; column > left; column--) {
          matrix[bottom][column] = arr[i];
          i++;
        }
        for (let row = bottom; row > top; row--) {
          matrix[row][left] = arr[i];
          i++;
        }
    }
  }

59. Spiral Matrix II

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-08-09
 * @modified
 *
 * @description 59. 螺旋矩阵 II
 * @description 59. Spiral Matrix II
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/spiral-matrix-ii/
 * @link https://leetcode-cn.com/problems/spiral-matrix-ii/
 * @solutions
 *
 * @best_solutions
 *
 */

export {};

const log = console.log;

function generateMatrix(n: number): number[][] {
  // 生成 1 ~ n**2 数组
  const arr = Array(n ** 2).fill(0).map((item, index) => index + 1);
  // 生成 n x n 矩阵
  const matrix: number[][] = Array(n).fill(0).map(i => []);
  // const matrix = [[1,2,3], [8,9,4], [7,6,5]];
  // 顺时针生成 matrix
  return matrixGenerator(n, matrix, arr);
};

// 矩阵生成器 n x n
function matrixGenerator(n: number, matrix: number[][], arr: number[]) {
  const len = matrix.length;
  let left = 0;
  let right = len - 1;
  let top = 0;
  let bottom = len - 1;
  // 动态更新 index
  let i = 0;
  while (left <= right && top <= bottom && i < arr.length) {
    for (let column = left; column <= right; column++) {
      matrix[top][column] = arr[i];
      i++;
    }
    for (let row = top + 1; row <= bottom; row++) {
      matrix[row][right] = arr[i];
      i++;
    }
    if (left < right && top < bottom) {
        for (let column = right - 1; column > left; column--) {
          matrix[bottom][column] = arr[i];
          i++;
        }
        for (let row = bottom; row > top; row--) {
          matrix[row][left] = arr[i];
          i++;
        }
    }
    [
      left,
      right,
      top,
      bottom,
    ] = [
      left + 1,
      right - 1,
      top + 1,
      bottom - 1,
    ];
  }
  return matrix;
};

// 1. 构造 空的 n x n 的 matrix
// 2. 螺旋遍历 matrix, 并且赋值 arr.shift();

// function matrixGenerator(n: number, matrix: number[][], arr: number[]) {
//   const len = matrix.length;
//   let left = 0;
//   let right = len - 1;
//   let top = 0;
//   let bottom = len - 1;
//   while (left <= right && top <= bottom && arr.length) {
//     for (let column = left; column <= right; column++) {
//       matrix[top][column] = arr.shift();
//     }
//     for (let row = top + 1; row <= bottom; row++) {
//       matrix[row][right] = arr.shift();
//     }
//     if (left < right && top < bottom) {
//         for (let column = right - 1; column > left; column--) {
//           matrix[bottom][column] = arr.shift();
//         }
//         for (let row = bottom; row > top; row--) {
//           matrix[row][left] = arr.shift();
//         }
//     }
//     [
//       left,
//       right,
//       top,
//       bottom,
//     ] = [
//       left + 1,
//       right - 1,
//       top + 1,
//       bottom - 1,
//     ];
//   }
//   return matrix;
// };



// 测试用例 test cases
const testCases = [
  {
    input: 3,
    result: [[1,2,3],[8,9,4],[7,6,5]],
    desc: 'value equal to [[1,2,3],[8,9,4],[7,6,5]]',
  },
  {
    input: 1,
    result: [[1]],
    desc: 'value equal to [[1]]',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const result = generateMatrix(testCase.input);
  log(`test case i result: `, result.join('') === testCase.result.join('') ? `passed ✅` : `failed ❌`, result);
  // log(`test case i =`, testCase);
}

// npx ts-node ./059\ spiral-matrix-ii.ts

https://leetcode.com/problems/spiral-matrix-ii/
https://leetcode.cn/problems/spiral-matrix-ii/

leetcode 题解 / LeetCode Solutions

https://www.youtube.com/results?search_query=+Leetcode+59

https://www.youtube.com/playlist?list=PLamwFu9yMruCBtS2tHUD77oI_Wsce-syE

https://www.youtube.com/channel/UCftIXZeipv4MTVwmfFphtYw/videos

https://neetcode.io/

https://github.com/neetcode-gh/leetcode/blob/main/javascript/54-Spiral-Matrix.js

https://github.com/neetcode-gh/leetcode/blob/main/typescript/54-Spiral-Matrix.js

类似问题

LeetCode

  1. Spiral Matrix

// 验证函数 (螺旋矩阵)
var spiralOrder = function(matrix: number[][]) {
  if (!matrix.length || !matrix[0].length) {
    return [];
  }
  const rows = matrix.length;
  const columns = matrix[0].length;
  const order: number[] = [];
  let left = 0;
  let right = columns - 1;
  let top = 0;
  let bottom = rows - 1;
  while (left <= right && top <= bottom) {
    for (let column = left; column <= right; column++) {
      order.push(matrix[top][column]);
    }
    for (let row = top + 1; row <= bottom; row++) {
      order.push(matrix[row][right]);
    }
    if (left < right && top < bottom) {
      for (let column = right - 1; column > left; column--) {
        order.push(matrix[bottom][column]);
      }
      for (let row = bottom; row > top; row--) {
        order.push(matrix[row][left]);
      }
    }
    [
      left,
      right,
      top,
      bottom
    ] = [
      left + 1,
      right - 1,
      top + 1,
      bottom - 1
    ];
  }
  return order;
};

https://leetcode.com/problems/spiral-matrix/
https://leetcode.cn/problems/spiral-matrix/

refs

https://www.cnblogs.com/xgqfrms/tag/matrix/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-08-17 00:01  xgqfrms  阅读(45)  评论(1编辑  收藏  举报