54. 螺旋矩阵
给你一个 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]
按照顺序,先填第一行,然后往下拐,然后左拐,然后右拐又回到了第一行,循环往复,直到填完整个矩阵
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ret = new LinkedList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return ret;
}
int rowMin = 0;
int colMin = 0;
int rowMax = matrix.length-1;
int colMax = matrix[0].length-1;
while (rowMin <= rowMax && colMin <= colMax) {
for (int i = colMin; i <= colMax; i++) {
ret.add(matrix[rowMin][i]);
}
rowMin++;
for (int i = rowMin; i <= rowMax; i++) {
ret.add(matrix[i][colMax]);
}
colMax--;
if (rowMin > rowMax || colMin > colMax) {
break;
}
for (int i = colMax; i >= colMin; i--) {
ret.add(matrix[rowMax][i]);
}
rowMax--;
for (int i = rowMax; i >= rowMin; i--) {
ret.add(matrix[i][colMin]);
}
colMin++;
}
return ret;
}
59. 螺旋矩阵 II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
class Solution {
public int[][] generateMatrix(int n) {
int count = 1;
int[][] ret = new int[n][n];
int rowMin = 0;
int colMin = 0;
int rowMax = n - 1;
int colMax = n - 1;
while (colMin <= colMax && rowMin <= rowMax) {
for (int i = colMin; i <= colMax; i++) {
ret[rowMin][i] = count;
count++;
}
rowMin++;
for (int i = rowMin; i <= rowMax; i++) {
ret[i][colMax] = count;
count++;
}
colMax--;
// if (rowMin > rowMax || colMin > colMax) {
// break;
// }
for (int i = colMax; i >= colMin; i--) {
ret[rowMax][i] = count;
count++;
}
rowMax--;
for (int i = rowMax; i >= rowMin; i--) {
ret[i][colMin] = count;
count++;
}
colMin++;
}
return ret;
}
}
2326. 螺旋矩阵 IV
给你两个整数:m 和 n ,表示矩阵的维数。
另给你一个整数链表的头节点 head 。
请你生成一个大小为 m x n 的螺旋矩阵,矩阵包含链表中的所有整数。链表中的整数从矩阵 左上角 开始、顺时针 按 螺旋 顺序填充。如果还存在剩余的空格,则用 -1 填充。
返回生成的矩阵
class Solution {
public int[][] spiralMatrix(int m, int n, ListNode head) {
int[][] ret = new int[m][n];
int rowMin = 0;
int colMin = 0;
int rowMax = m - 1;
int colMax = n - 1;
ListNode pre = head;
while (colMin <= colMax && rowMin <= rowMax) {
for (int i = colMin; i <= colMax; i++) {
if (pre != null) {
ret[rowMin][i] = pre.val;
pre = pre.next;
} else {
ret[rowMin][i] = -1;
}
}
rowMin++;
for (int i = rowMin; i <= rowMax; i++) {
if (pre != null) {
ret[i][colMax] = pre.val;
pre = pre.next;
} else {
ret[i][colMax] = -1;
};
}
colMax--;
if (rowMin > rowMax || colMin > colMax) {
break;
}
for (int i = colMax; i >= colMin; i--) {
if (pre != null) {
ret[rowMax][i] = pre.val;
pre = pre.next;
} else {
ret[rowMax][i] = -1;
}
}
rowMax--;
for (int i = rowMax; i >= rowMin; i--) {
if (pre != null) {
ret[i][colMin] = pre.val;
pre = pre.next;
} else {
ret[i][colMin] = -1;
}
}
colMin++;
}
return ret;
}
}