大家好,至於説好的每天一道算法題呢?是有原因的,之前每天跑跑跑找工作,極度消耗精力的。現在決定冷靜一下,練一下算法,復習一下計算機網絡,操作系統。感受一下大四生活呢。
今天為大家帶來的是蛇形矩陣,大概描述一下就是這樣的,就是將下面這個數組,然後輸出:
1 2 3 4 5 6 7 8 9 10 11 11 13 14 15 16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
對了我使用的是typescript
下面貼上代碼吧,如果有時間就再天上注釋1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66class cont{
flag:number = 0;
nti:number;
ntj:number;
xy;
constructor(){
}
conFlag(i,j){
this.nti = i;
this.ntj = j;
this.flag = (this.flag+1) % 4;
}
access(i,j,width,height){
console.log(this.flag);
switch(this.flag){
case 1:
if (this.ntj<j+width){
this.ntj++;
}break;
case 2:
if (this.nti<i+height) {
this.nti++;
}break;
case 3:
if (this.ntj>j-width){
this.ntj--;
}break;
case 0:
if (this.nti>=i-height){
this.nti--;
}break;
}
this.xy = {
x:this.nti,
y:this.ntj
}
}
}
var ob = new cont();
function snake(Arr, i, j, width, height){
if(width==0||height==0){
return;
}
ob.conFlag(i,j);
var flag = ob.flag %2;
switch(flag){
case 1:for(var k = 0;k<width;k++){
ob.access(i,j,width,height);
var xy = ob.xy;
var xyx,xyy;
xyx = xy.x;xyy = xy.y;
console.log(xyx,xyy,Arr[xyx][xyy]);
};
snake(Arr,xyx,xyy,width,height-1);
break;
case 0:for(var k = 0;k<height;k++){
ob.access(i,j,width,height);
var xy = ob.xy;
var xyx,xyy;
xyx = xy.x;xyy = xy.y;
console.log(xyx,xyy,Arr[xyx][xyy]);
};
snake(Arr,xyx,xyy,width-1,height);
break;
}
}
調用方法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16var Arr = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
];
snake(Arr, 0, -1, 4, 4);//注意初始的時候確實是-1
var Brr = [
[1,2,3],
[12,13,4],
[11,14,5],
[10,15,6],
[9,8,7]
];
snake(Brr,0,-1,3,5);//snake(Brr,0,-1,Brr.length,Brr[0].length);
我的輸入法怎麽成了繁體了,奇怪。。。總之呢測了一下,沒有bug了
###精简版来了,那天因为特殊需求花了二十分钟重新做了一遍,这次是js的1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72var clockwise = function(arr){
var flag = 0;
var height = arr.length;
if(height){
var width = arr[0].length;
}
function fn(arr, i, j, width, height) {
var compass;
if (flag == 2 || flag == 0) {
compass = width;
} else {
compass = height;
}
for (var index = 0; index < compass; index++) {
switch (flag) {
case 0:
j++;
break;
case 1:
i++;
break;
case 2:
j--;
break;
case 3:
i--;
break;
}
if (arr[i][j]) {
console.log(arr[i][j]);
} else {
console.log(i, j);
return;
// break;
}
}
switch (flag) {
case 0:
height--;
break;
case 1:
width--;
break;
case 2:
height--;
break;
case 3:
width--;
break;
}
if (width == 0 || height == 0) {
return;
}else{
flag = (flag + 1) % 4;
fn(arr, i, j, width, height);
}
return;
}
fn(arr, 0, -1, width, height);
};
// var flag = 0;
var Arr = [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]];
clockwise(Arr);
var Brr = [
[1,2,3],
[12,13,4],
[11,14,5],
[10,15,6],
[9,8,7]
];
clockwise(Brr);