我是靠谱客的博主 纯真铃铛,这篇文章主要介绍java按照顺时针顺序打印数组的值,现在分享给大家,希望可以做个参考。

6/10

复制代码
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
public class Work { /** * 该方法实现 按照顺时针顺序打印数组的值, * * 定义四个边界:上(top)、下(down)、左(left)、右(right),坐标需要在边界内进行遍历。 定义一个长度为2的数组 direction 指定坐标变化的方向,[row, column]为当前的坐标,那么[row + direction[0], column + direction[1]]即为坐标的下一个位置。通过这种方式,只要注意更新 direction 即可 坐标每遍历到一个角落,direction就应该发生变化,同时边界也应该发生变化: 遍历到右上角,此时direction应该变为向下,上边界应该增加1 遍历到右下角,此时direction应该变为向左,右边界应该减少1 遍历到左下角,此时direction应该变为向上,下边界应该减少1 遍历到左上角,此时direction应该变为向右,左边界应该增加1 怎么判断是否到达哪个角落呢? 可以通过坐标和边界值以及方向来判断 比如如果到达了右上角。此时横坐标应该等于right,因为是顺时针遍历,所以纵坐标应该等于top,且方向应该为向右。 * */ public static int[] spiralOrder(int[][] matrix) { if(matrix.length == 0) { return new int[] {}; } int totalNumber = matrix.length * matrix[0].length; //结果数组,按照顺时针访问矩阵的顺序,存放矩阵元素 int[] ret = new int[totalNumber]; //index指向结果数组中,按照顺时针访问的下一个矩阵元素的值,在结果数组中存放的位置 int index = 0; //上边界 int top = 0; //下边界(矩阵最后一行的索引) int down = matrix.length - 1; //左边界 int left = 0; //右边界 int right = matrix[0].length - 1; //按照顺时针方式,下一步的移动的方式,取值和含义如下 //(0,1)表示行数不变, 向右移动一个位置 //(0,-1)表示行数不变,向左移动一个位置 //(1,0) 表示列数不变,向下移动一个位置 //(-1,0)表示列数不变,向上移动一个位置 int[] direction = new int[]{0, 1}; int row = 0, column = 0; int count = (down + 1) * (right + 1); // while (totalNumber > 0) { //把按顺时针顺序访问到的元素,存储到结果集中的第index下标 ret[index++] = (matrix[row][column]); //还没有遍历到的元素个数,少了一个 totalNumber--; if (row == top && column == right && direction[1] == 1) { //如果是在水平向右移动的过程中,移动到了右边界,修改移动方向和,上边界的值(这行已经遍历完了) direction[0] = 1; direction[1] = 0; top++; } else if (row == down && column == right && direction[0] == 1) { //如果是在垂直向下移动的过程中,移动到了下边界,修改移动方向和,右边界(右面这列遍历完了) direction[0] = 0; direction[1] = -1; right--; } else if (row == down && column == left && direction[1] == -1) { //如果是在水平向左移动的过程中,移动到了左边界,修改移动方向和,下边界的值(下面这行已经遍历完了) direction[0] = -1; direction[1] = 0; down--; } else if (row == top && column == left && direction[0] == -1) { //如果是在垂直向上移动的过程中,移动到了上边界,修改移动方向和,左边界(左面这列遍历完了) direction[0] = 0; direction[1] = 1; left++; } //按计算好的顺时针移动方式,移动到一下个位置 row += direction[0]; column += direction[1]; } return ret; } }

最后

以上就是纯真铃铛最近收集整理的关于java按照顺时针顺序打印数组的值的全部内容,更多相关java按照顺时针顺序打印数组内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(84)

评论列表共有 0 条评论

立即
投稿
返回
顶部