Skip to content

Commit fac36a3

Browse files
committed
添加顺时针打印矩阵的经典思路解法以及添加顺时针旋转矩阵的解法
1 parent 801e48a commit fac36a3

File tree

2 files changed

+93
-1
lines changed

2 files changed

+93
-1
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/******
2+
*
3+
*
4+
* 将正方形矩阵顺时针旋转 90 度
5+
*
6+
* 主要是明白 外面的一个框怎么旋转
7+
*
8+
*/
9+
10+
function rotateSquareMatrix(matrix) {
11+
var lr = 0;
12+
var lc = 0;
13+
var rr = matrix.length - 1;
14+
var rc = matrix[0].length - 1;
15+
16+
this.rotateEdge = function (matrix, tlr, tlc, trr, trc){
17+
var allnum = trr - tlr;
18+
var tempdata = 0;
19+
for (let i = 0; i < allnum; i++) {
20+
tempdata = matrix[tlr][tlc + i];
21+
matrix[tlr][tlc + i] = matrix[trr - i][tlc];
22+
matrix[trr - i][tlc] = matrix[trr][trc - i];
23+
matrix[trr][trc - i] = matrix[tlr + i][trc];
24+
matrix[tlr + i][trc] = tempdata;
25+
}
26+
}
27+
28+
while (lr < rr){
29+
this.rotateEdge(matrix, lr++, lc++, rr--, rc--);
30+
}
31+
32+
return matrix;
33+
}
34+
35+
36+
var matrix = [];
37+
matrix[0] = [1, 2, 3, 4];
38+
matrix[1] = [5, 6, 7, 8];
39+
matrix[2] = [9, 10, 11, 12];
40+
matrix[3] = [13, 14, 15, 16];
41+
42+
console.log(rotateSquareMatrix(matrix));

NowCoder/Leetcode/printMatrixbyClockwise.js

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,55 @@ function printMatrix(matrix) {
4646
return output;
4747
}
4848

49+
50+
// 使用经典思路解答矩阵打印问题
51+
function printMatrix2(matrix) {
52+
var lr = 0,lc=0; // lr = left row, lc = left column 左上角开始的坐标
53+
var rr = matrix.length-1; // rr = right row
54+
var rc = matrix[0].length-1; // rc = right column 右下角坐标
55+
var output = [];
56+
57+
this.printEdge = function(matrix, tlr,tlc,trr,trc){
58+
if (tlr === trr) {
59+
for (let i = tlc; i <=trc; i++) {
60+
output.push(matrix[tlr][i]);
61+
}
62+
} else if (tlc === trc) {
63+
for (let i = tlr; i <=trr; i++) {
64+
output.push(matrix[i][tlc]);
65+
}
66+
} else {
67+
var curlr = tlr; // 获取当前行
68+
var curlc = tlc; // 获取当前列
69+
while (curlc !== trc) {
70+
output.push(matrix[tlr][curlc]);
71+
curlc++;
72+
}
73+
while(curlr !== trr) {
74+
output.push(matrix[curlr][trc]);
75+
curlr++;
76+
}
77+
while(curlc !== tlc){
78+
output.push(matrix[trr][curlc]);
79+
curlc--;
80+
}
81+
while(curlr !== tlr){
82+
output.push(matrix[curlr][tlc]);
83+
curlr--;
84+
}
85+
}
86+
}
87+
88+
// 每次打印由左上角和右下角组成的一个框
89+
// 左上角的行 小于等于 右下角的行 左上角的列 小于等于 右下角的列
90+
while(lr <= rr && lc <= rc){
91+
this.printEdge(matrix, lr++, lc++, rr--, rc--);
92+
}
93+
return output;
94+
}
95+
96+
97+
4998
var matrix = [];
5099
// matrix[0] = [1,2,3,4];
51100
// matrix[1] = [5,6,7,8];
@@ -56,4 +105,5 @@ matrix[1] = [3,4];
56105
matrix[2] = [5,6];
57106
matrix[3] = [7,8];
58107

59-
console.log(printMatrix(matrix));
108+
console.log(printMatrix(matrix));
109+
console.log(printMatrix2(matrix));

0 commit comments

Comments
 (0)