leetcode矩阵问题

54. 螺旋矩阵

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
private List<Integer> result;
//一圈一圈进行打印,当左上角元素在右下角元素的上方或者右方时结束
public List<Integer> spiralOrder(int[][] matrix) {
result = new ArrayList<>();
if(matrix.length==0||matrix[0].length==0){
return result;
}
int left_row = 0;
int left_col = 0;
int right_row = matrix.length-1;
int right_col = matrix[0].length-1;
while(left_row<=right_row&&left_col<=right_col){
helper(matrix,left_row++,left_col++,right_row--,right_col--);
}
return result;
}

/**打印一圈元素局灶性,这实际上是一个矩形,需要传递该矩形的左上角以及左下角坐标
* 当两个坐标同行,直接打印
* 当两个坐标同列,直接打印
* 两个坐标不同行也不同列:
*
*/
public void helper(int[][] matrix,int left_row,int left_col,int right_row,int right_col){
if(left_row==right_row){
for(int i= left_col;i<=right_col;i++){
result.add(matrix[left_row][i]);
}
}else if(left_col==right_col){
for(int i= left_row;i<=right_row;i++){
result.add(matrix[i][left_col]);
}
}else{
int curCol = left_col;
while(curCol!=right_col){
result.add(matrix[left_row][curCol]);
curCol++;
}
int curRow = left_row;
while(curRow!=right_row){
result.add(matrix[curRow][right_col]);
curRow++;
}

while(curCol!=left_col){
result.add(matrix[right_row][curCol]);
curCol--;
}
while(curRow!=left_row){
result.add(matrix[curRow][left_col]);
curRow--;
}
}
}

498. 对角线遍历

1576572207688

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
/**
* 当a点走完最后一个点,可以结束循环
* 执行完一次对角线打印,坐标变换方式:
* b:先下,走到底了,再右
* a:先右,走到最右,再下
* */
private int arr_index= 0;
public int[] findDiagonalOrder(int[][] matrix) {

if(matrix.length==0||matrix[0].length==0){
return new int[0];
}
int[] result = new int[matrix.length*matrix[0].length];
arr_index = 0;
boolean form = false;
int row_lenth = matrix.length-1;
int col_length = matrix[0].length-1;
int a_row =0,b_row = 0,a_col=0,b_col=0;
//a到达最后一个节点
while(a_row<=row_lenth){
helper(matrix,a_row,a_col,b_row,b_col,form,result);
if(a_col<col_length){
a_col++;
}else{
a_row++;
}
if(b_row<row_lenth){
b_row++;
}else{
b_col++;
}
form=!form;
}
return result;

}
/**
* 打印一个对角,a为右上角元素,b为左下角元素
* 因为有左到右以及右到左两种方式交替,所以需要一个form参数
* 右到左:a_row>=b_row 赋值 移动到做下第一个点:a_row-- a_col--
* */
public void helper(int[][] matrix,int a_row,int a_col,int b_row,int b_col,boolean form,int[] result){
if(form){
while(a_row<=b_row&&a_col>=b_col){
result[arr_index++] = matrix[a_row++][a_col--];
}
}else{
while(a_row<=b_row&&a_col>=b_col){
result[arr_index++] = matrix[b_row--][b_col++];
}
}
}