This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
The topic of dry
Enter a matrix and print out each number in clockwise order from the outside in.
Example 1:
Input: matrix = [[1, 2, 3], [4 and 6], [7,8,9]] output:,2,3,6,9,8,7,4,5 [1]Copy the code
Example 2:
Input: matrix = [[1, 2, 3, 4], [5,6,7,8], [9,10,11,12]] output:,2,3,4,8,12,11,10,9,5,6,7 [1]Copy the code
Solution:
When you see this problem, call me good guy. Is this a simple problem? Force buckle classification simply SAO do not.
To print a two-dimensional array clockwise, we first draw an array:
We first need to define four pointer variables to represent our Top, Bottom, Left, and Right positions.
- When we go through the first row, the Top goes down
- I’m going to go through the Right vertical row, and when I’m done, I’m going to move Right to left
- And then I’m going to iterate over the last row, and then I’m going to move the Bottom up
- Then walk through the Left vertical line, Left and right after the end of the walk
The condition that we end the loop is that we end the loop when we Top>Bottom or Right<Left or Bottom>Top or Left>Right, respectively
Code implementation:
/ * * *@param {number[][]} matrix
* @return {number[]}* /
var spiralOrder = function (matrix) {
if (matrix.length == 0) return []
let left = 0;
let top = 0;
let right = matrix[0].length - 1;
let bottom = matrix.length - 1
let res = [];
while (true) {
for (let i = left; i <=right; i++) {
res.push(matrix[top][i]);
}
top += 1;
if (top > bottom) break
for (let i = top; i <= bottom; i++) {
res.push(matrix[i][right]);
}
right -= 1;
if (right < left) break
for (let i = right; i >= left; i--) {
res.push(matrix[bottom][i]);
}
bottom -= 1;
if (bottom < top) break
for (let i = bottom; i >=top; i--) {
res.push(matrix[i][left]);
}
left += 1;
if (left > right) break
}
return res
};
Copy the code
Simple analysis of the following code:
We order according to our analysis in the loop to a traverse each row or column of data, data will be pushed to a new array, and at the end of each traversal will we move the location of the pointer accordingly, once encounter our end conditions will directly out of the loop, it shows that we have traversed out of this can be the two-dimensional matrix