代码拉取完成,页面将自动刷新
package pers.vic.basics.leetcode;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;
/**
* @description: 54. 螺旋矩阵 {@literal https://leetcode-cn.com/problems/spiral-matrix/}
* @author Vic.xu
* @date: 2020/12/15 0015 11:24
*/
public class J0054_M_54 {
/*
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,
返回矩阵中的所有元素。
*/
/**
* 顺时针螺旋顺序
*/
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int startRow = 0;
int endRow = matrix.length - 1;
int startColumn = 0;
int endColumn = matrix[0].length - 1;
while (startRow <= endRow && startColumn <= endColumn) {
//左往右
for (int i = startColumn; i <= endColumn; i++) {
res.add(matrix[startRow][i]);
}
//上往下
startRow++;
for (int i = startRow; i <= endRow; i++) {
res.add(matrix[i][endColumn]);
}
endColumn--;
//在进行--操作的时候 需要再次判断是否满足while 条件
//右往左
if (startRow <= endRow && startColumn <= endColumn) {
for (int i = endColumn; i >= startColumn; i--) {
res.add(matrix[endRow][i]);
}
}
endRow--;
//下往上
if (startRow <= endRow && startColumn <= endColumn) {
for (int i = endRow; i >= startRow; i--) {
res.add(matrix[i][startColumn]);
}
}
startColumn++;
}
return res;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 7},
{4, 5, 7, 6},
{7, 8, 9, 9}};
List<Integer> list = spiralOrder(matrix);
String collect = list.stream().map(String::valueOf).collect(Collectors.joining("->"));
System.out.println(collect);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。