彪码野郎

  • 首页

  • 分类

  • 归档

旋转打印矩阵

发表于 2019-08-28 分类于 数据结构与算法 阅读次数:

题目

思路

我们的矩阵可以看成是多个圈结合再在一起的,当我们能输出一个圈,其他的圈也能用同样的方法输出,下面来看一下如何输出一个圈

除了常规情况外,仍需注意线性的矩形即一条直线(横或竖)

注意在实现代码时,我们应注意二维数组的定位与实际坐标轴定位的差异

下面我们来看下具体的实现

实现

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
public static void spiralOrderPrint(int[][] matrix) {

int x1 = 0;
int x2 = matrix.length -1;
int y1 = 0;
int y2 = matrix[0].length - 1;
System.out.println();
while(x1 <= x2 && y1 <= y2) {
//每打印完一圈,圈的范围就缩小1,直到其中一个坐标越界
printEdge(matrix,x1++, x2-- ,y1++, y2--);
}

}

public static void printEdge(int[][] m, int x1, int x2, int y1, int y2) {

if(x1 == x2) { //只有一列
for(int i = y1; i <= y2 ; i++ ) {
System.out.print(m[x1][i] + " ");
}
} else if(y1 == y2) { //只有一行
for(int i = x1; i <= x2; i++) {
System.out.print(m[i][y1] + " ");
}
} else { //常规情况
int currentX = x1;
int currentY = y1;
//此处需要注意二维数组你想改变其横坐标,应该是对y进行操作,反之改变纵坐标,应该对x操作
while(currentY < y2) { //向右移动
System.out.print(m[currentX][currentY] + " ");
currentY++;
}

while(currentX < x2) { //向下移动
System.out.print(m[currentX][currentY] + " ");
currentX++;
}
while(currentY > y1) { //向左移动
System.out.print(m[currentX][currentY] + " ");
currentY--;
}
while(currentX > x1) { //向上移动
System.out.print(m[currentX][currentY] + " ");
currentX--;
}

}
}

相关练习:输出旋转90°后的矩阵

# 面试题
经典老番:猫狗队列
输出旋转90°后的矩阵
  • 文章目录
  • 站点概览
Weapon

Weapon

40 日志
6 分类
4 标签
  1. 1. 题目
  2. 2. 思路
  3. 3. 实现
© 2019 Weapon
由 Hexo 强力驱动 v3.9.0
|
主题 – NexT.Pisces v7.3.0