java实现转圈打印矩阵算法

2025-05-29 0 62

本文实例为大家分享了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--;

}

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/seagal890/article/details/79124067

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java实现转圈打印矩阵算法 https://www.kuaiidc.com/109872.html

相关文章

发表评论
暂无评论