1 Star 0 Fork 0

临窗旋墨 / basics

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
J0054_M_54.java 2.10 KB
一键复制 编辑 原始数据 按行查看 历史
临窗旋墨 提交于 2020-12-15 15:14 . leetcode 54 螺旋输出矩阵
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);
}
}
Java
1
https://gitee.com/xuqiudong/basics.git
git@gitee.com:xuqiudong/basics.git
xuqiudong
basics
basics
master

搜索帮助