本文實例為大家分享了java實現轉圈打印矩陣的具體代碼,供大家參考,具體內容如下
給定一個整形矩陣matrix,請按照順時針方向轉圈的方式,輸入(打印)元素值。
例如:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
輸出結果為:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
要求:額外空間復雜度為o(1)
java代碼如下:
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
|
package com.bean.algorithmexec; public class matrixdemo { /* * 給定一個整形矩陣matrix,請按照順時針方向轉圈的方式,輸入(打印)元素值。 * 例如: * 1 2 3 4 * 5 6 7 8 * 9 10 11 12 * 13 14 15 16 * 輸出結果為:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 * * 要求:額外空間復雜度為o(1) * */ public static void main(string[] args) { // todo auto-generated method stub //初始化一個 4*4的整形矩陣,從第一行第一列從左向右,第二行,第三行,直到第四行依次賦值 1,2,...16. int [][] matrixdemo= new int [ 4 ][ 4 ]; matrixdemo=creatematrix(); printmatrix(matrixdemo); //轉圈打印 spiralorderprint(matrixdemo); } private static int [][] creatematrix() { // todo auto-generated method stub int matrix[][]= new int [ 4 ][ 4 ]; int k= 1 ; for ( int i= 0 ;i< 4 ;i++) { for ( int j= 0 ;j< 4 ;j++) { matrix[i][j]=k; k++; } } return matrix; } //順序打印矩陣元素 private static void printmatrix( int [][] matrix) { for ( int i= 0 ;i< 4 ;i++) { for ( int j= 0 ;j< 4 ;j++) { system.out.print(matrix[i][j]+ "\t" ); } system.out.println(); } } //轉圈打印 private static void spiralorderprint( int [][] matrix) { int tr= 0 ; int tc= 0 ; int dr=matrix.length- 1 ; int dc=matrix[ 0 ].length- 1 ; while (tr<=dr && tc<=dc) { printedge(matrix, tr++, tc++, dr--,dc--); } } private static void printedge( int [][] matrix, int tr, int tc, int dr, int dc) { // todo auto-generated method stub if (tr==dr) { //子矩陣只有一行時 for ( int i=tc;i<=dc;i++) { system.out.print(matrix[tr][i]+ " " ); } } else if (tc==dc) { //子矩陣只有一列時 for ( int i=tr;i<=dr;i++){ system.out.print(matrix[i][tc]+ " " ); } } else { //一般情況 int curc=tc; int curr=tr; while (curc!= dc) { system.out.print(matrix[tr][curc]+ " " ); curc++; } while (curr!= dr) { system.out.print(matrix[curr][dc]+ " " ); curr++; } while (curc!= tc) { system.out.print(matrix[dr][curc]+ " " ); curc--; } while (curr!= tr) { system.out.print(matrix[curr][tc]+ " " ); curr--; } } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/seagal890/article/details/79124067