首页 > 编程语言 >LeetCode 螺旋矩阵 II 算法题解 All In One

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

时间:2022-08-17 00:12:43浏览次数:107  
标签:matrix bottom 题解 top II let row LeetCode left

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

<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/NO1zLdOwgR0?start=4" title="YouTube video player" width="560"></iframe> <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/BJnMZNwUk1M?start=2" title="YouTube video player" width="560"></iframe>

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/


Flag Counter

©xgqfrms 2012-2020

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

原创文章,版权所有©️xgqfrms, 禁止转载

标签:matrix,bottom,题解,top,II,let,row,LeetCode,left
From: https://www.cnblogs.com/xgqfrms/p/16593473.html

相关文章

  • leetcode85-最大矩形
    最大矩形dp+单调栈对每一层维护本列中形成的最高值height,然后对每一层分别计算最大的矩形。计算每一层最大矩形的时候,先用单调栈记录小于当前位置的左下标和右下标,矩......
  • iis占用服务器内存,W3wp.exe 进程占用内存高消耗CPU近100%导致网站反应速度缓慢的解决
    iis占用服务器内存,W3wp.exe进程占用内存高消耗CPU近100%导致网站反应速度缓慢的解决方案如何降低W3WP.EXE占用的内存和CPU?结合网上的诸多建议,主要的解决办法是:a.在I......
  • leetcode1175-质数排列
    质数排列分别找出质数和合数的数量,将两者的阶乘相乘即可classSolution{publicintnumPrimeArrangements(intn){intcnt=0;for(inti=2;......
  • 转载:Windows Server查看W3SVC IIS服务器中对应的网站日志
    W3SVC日志文件夹中序号的含义,格式就是W3SVC+网站ID如果没有自定义站点的日志路径,日志默认的路径是C:\inetpub\logs\LogFiles\基本上每个网站存放日志的文件夹名称都是以W......
  • leetcode690-员工的重要性
    员工的重要性dfsclassSolution{Map<Integer,Employee>map=newHashMap<>();publicintgetImportance(List<Employee>employees,intid){......
  • leetcode1033-移动石子直到连续
    移动石子直到连续分类讨论classSolution{publicint[]numMovesStones(inta,intb,intc){if(a>b){intt=a;a=b;b=t;}if(a>......
  • ARC094D题解
    设\(A<B\),\(C=\max(\sqrt{AB-1},A)\),答案为:\[C-1+\frac{AB-1}{C+1}\]如果\(A>B\)时显然可以互换,接下来称\(A\)所在的比赛为第一场比赛,\(B\)所在的比赛为第二场比赛......
  • 题解 [ZJOI2010]排列计数
    好题。%你赛考到了不会摆烂,后来发现原来有向下取整,题面没有。。。(就算有我也做不出来啦qAq首先我们会发现这个长得就是小根堆,答案就变成了小根堆的计数。首先最小的......
  • leetcode-双指针-21
    /**<p>给你一个数组<code>nums</code><em></em>和一个值<code>val</code>,你需要<strong><ahref="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3......
  • ubuntu16.04中文乱码问题解决
    1、先输入locale-a,查看一下现在已安装的语言2、若不存在如zh_CN之类的语言包,进行中文语言包装:apt-getinstalllanguage-pack-zh-hans3、安装好后我们可以进行临时修......