-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMyMatrix.java
More file actions
125 lines (96 loc) · 3.14 KB
/
Copy pathMyMatrix.java
File metadata and controls
125 lines (96 loc) · 3.14 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package mypkg.practice.javacore;
/**
* Created by Path on 2017/3/25.
*/
public class MyMatrix {
// private int nr_row;
// private int nr_col;
// private int[][] matrix;
// public MyMatrix(int[][] m, int row, int col) {
// nr_row = row;
// nr_col = col;
// matrix = new int[row][col];
// for (int i = 0; i < row; i++) {
// System.arraycopy(m[i], 0, matrix[i], 0, col);
// }
// }
public static void showIt(int[][] m, int row, int col) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
System.out.printf("%2d ", m[i][j]);
}
System.out.println();
}
}
public static void roundPrint(int[][] m, int row, int col) {
int left = 0;
int right = col - 1;
int top = 0;
int bottom = row - 1;
int total = col * row;
int[] OutestLayer;
int[] arrayMatrix = new int[total];
int cnt = 0;
int LayerLen;
while (cnt < total) {
if (right == left)
LayerLen = bottom - top + 1;
else if (bottom == top)
LayerLen = right - left + 1;
else
LayerLen = (right - left + bottom - top) * 2;
// System.out.printf("left = %d\n", left);
// System.out.printf("top = %d\n", top);
// System.out.printf("LayerLen = %d\n", LayerLen);
OutestLayer = getOutestLayer(m, left, right, top, bottom, LayerLen);
System.arraycopy(OutestLayer, 0, arrayMatrix, cnt, LayerLen);
cnt += LayerLen;
left++;
right--;
top++;
bottom--;
}
for (int e : arrayMatrix) {
System.out.printf("%d ", e);
}
}
private static int[] getOutestLayer(int[][] m, int left, int right, int top, int bottom,
int LayerLen) {
int[] OutestLayer;
int cur_row;
int cur_col;
int cnt;
OutestLayer = new int[LayerLen];
if (right < left || bottom < top)
return OutestLayer;
cnt = 0;
OutestLayer[cnt++] = m[top][left];
for (cur_col = left + 1; cur_col <= right; cur_col++)
OutestLayer[cnt++] = m[top][cur_col];
for (cur_row = top + 1; cur_row <= bottom; cur_row++)
OutestLayer[cnt++] = m[cur_row][right];
if (cnt >= LayerLen)
return OutestLayer;
for (cur_col = right - 1; cur_col >= left; cur_col--)
OutestLayer[cnt++] = m[bottom][cur_col];
for (cur_row = bottom - 1; cur_row > top; cur_row--)
OutestLayer[cnt++] = m[cur_row][left];
return OutestLayer;
}
public static void main(String[] args) {
int row;
int col;
row = 5;
col = 7;
int[][] m = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
m[i][j] = i * col + j + 1;
}
}
showIt(m, row, col);
System.out.println();
roundPrint(m, row, col);
}
}