螺旋矩阵
问题描述:
给你一个
m
行n
列的矩阵matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]思路分析:
采用伴随矩阵visited来标记已经遍历过的元素
使用方向矩阵directions来控制移动方
//提交版
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
// 创建储存顺时针的列表
List<Integer> order = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
return order;
}
int rows = matrix.length;
int columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int row = 0;
int column = 0;
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
int directionIndex = 0;
for (int i = 0; i < total; i++){
order.add(matrix[row][column]);
//已经访问过的进行标记
visited[row][column] = true;
int nextrow = row + directions[directionIndex][0];
int nextcolumn =column + directions[directionIndex][1];
if (nextrow<0||nextrow>=rows||nextcolumn<0||nextcolumn>=columns||visited[nextrow][nextcolumn])
directionIndex = (directionIndex+1)%4;
row = row + directions[directionIndex][0];
column = column + directions[directionIndex][1];
}
return order;
}
}
//带有输入输出版
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class hot_16spiralOrder {
public List<Integer> spiralOrder(int[][] matrix){
// 创建储存顺时针的列表
List<Integer> order = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
return order;
}
int rows = matrix.length;
int columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int row = 0;
int column = 0;
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
int directionIndex = 0;
for (int i = 0; i < total; i++){
order.add(matrix[row][column]);
//已经访问过的进行标记
visited[row][column] = true;
int nextrow = row + directions[directionIndex][0];
int nextcolumn =column + directions[directionIndex][1];
if (nextrow<0||nextrow>=rows||nextcolumn<0||nextcolumn>=columns||visited[nextrow][nextcolumn])
directionIndex = (directionIndex+1)%4;
row = row + directions[directionIndex][0];
column = column + directions[directionIndex][1];
}
return order;
}
public static void main(String[] args){
int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
System.out.println("输入:" + Arrays.deepToString(matrix));
hot_16spiralOrder hot16spiralOrder = new hot_16spiralOrder();
List<Integer> result = hot16spiralOrder.spiralOrder(matrix);
System.out.println("输出" + result);
}
}
知识点总结:
方向矩阵的计算方式:
directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
directionIndex = (directionIndex +1)% 4
directionIndex = 0
:表示向右移动(0, 1)
。
directionIndex = 1
:表示向下移动(1, 0)
。
directionIndex = 2
:表示向左移动(0, -1)
。
directionIndex = 3
:表示向上移动(-1, 0)
。