Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of rotating two-dimensional Array by JavaScript

Shulou Source: shulou.com Published: 2022-05-31 19:15:05 09月21日 Update

This article mainly explains the "JavaScript rotation two-dimensional array method", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn the "JavaScript rotation two-dimensional array method"!

Description of the topic

Given an n × n two-dimensional matrix matrix represents an image. Please rotate the image 90 degrees clockwise.

You have to rotate the image in place, which means you need to modify the input two-dimensional matrix directly. Please do not use another matrix to rotate the image.

Example 1:

Input: matrix = [1, 2, 3], [4, 5, 5, 6], [7, 8, 9]]

Output: [[7rem 4rem 1], [8pr 5rem 2], [9pr 6pr 3]]

Example 2:

Input: matrix = [5 record1, 9], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 14, 12, 16]

Output: [15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]

Second, ideas and realization

You can see from the example figure:

After the array is rotated 90 degrees clockwise, column 1 becomes row 1, column 2 becomes row 2, and column 3 becomes row 3.

To achieve one:

/ * * @ param {number []} matrix* @ return {void} Do not return anything, modify matrix in-place instead.*/var rotate = function (matrix) {let n = matrix.length;let res = new Array (n) .fill (0). Map (() = > new Array (n) .fill (0)); for (let I = 0; I

< n; i++)for (let j = n - 1; j >

= 0; return res; -) res [I] [n-j-1] = matrix [j] [I]; return res;}

Time complexity: O (N ^ 2), where N is the side length of matrix

Space complexity: O (N ^ 2). We need to use an auxiliary array of the same size as matrix.

There is another way of thinking:

Mirror symmetry according to the diagonal from the upper left to the lower right

Invert each row of the matrix

Like this:

/ * * @ param {number []} matrix* @ return {void} Do not return anything, modify matrix in-place instead.*/var rotate = function (matrix) {let n = matrix.length;// first mirror the symmetric two-dimensional matrix for (let I = 0; I) along the diagonal

< n; i++) {for (let j = i; j < n; j++) {[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];}}const reverseRow = (arr) =>

{let I = 0BI j = arr.length-1bot while (I

Tags: Two-dimensional array matrix method complexity image complexity idea example learning input symmetry line content diagonal diagonal that is clockhand time space Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL Shulou Technology Docker Shulou Tech Info