螺旋矩阵
给你一个 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]
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210408171010482.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzkxMTk2OQ==,size_16,color_FFFFFF,t_70
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
思路:这是一个从外往内的环,我们只要模拟他的路线即可
代码:
public List<Integer> spiralOrder(int[][] matrix) {
// 行
int row = matrix.length;
// 列
int col = matrix[0].length;
int left = 0, right = col - 1, top = 0, bottom = row - 1;
ArrayList<Integer> list = new ArrayList<>();
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
list.add(matrix[top][column]);
}
for (row = top + 1; row <= bottom; row++) {
list.add(matrix[row][right]);
}
if (left < right && top < bottom) {
for (col = right - 1; col > left; col--) {
list.add(matrix[bottom][col]);
}
for (row = bottom; row > top; row--) {
list.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return list;
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
螺旋矩阵II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
思路:在上面我们模拟了他的线路,所以我们直接可以借用过来,利用index计数,来进行赋值
代码:
public int[][] generateMatrix(int n) {
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int[][] sum = new int[n][n];
int index = 1;
while (left <= right && top <= bottom) {
for (int col = left; col <= right; col++) {
sum[top][col] = index++;
}
for (int row = top + 1; row <= bottom; row++) {
sum[row][right] = index++;
}
if (left < right && top < bottom) {
for (int col = right - 1; col > left; col--) {
sum[bottom][col]=index++;
}
for (int row = bottom; row > top; row--) {
sum[row][left] = index++;
}
}
left++;
right--;
top++;
bottom--;
}
return sum;
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii