力扣数组篇——螺旋矩阵
剑指 Offer 29. 顺时针打印矩阵,输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
思想:按照上右下左的顺序进行遍历,结束循环的方式是矩阵中的所有元素均输出。
难点:边界的选择
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0){
return new int[]{};
}
int rows = matrix.length;
int columns = matrix[0].length;
int left = 0,right = columns - 1,top = 0, bottom = rows - 1;
int index = 0;
int len = rows * columns;
int[] res = new int[len];
while(len >= 1){
for(int i=left;i<=right && len >= 1;i++){
res[index++] = matrix[top][i];
len--;
}
top++;
for(int i=top;i<=bottom && len >= 1;i++){
res[index++] = matrix[i][right];
len--;
}
right--;
for(int i=right;i>=left && len >= 1;i--){
res[index++] = matrix[bottom][i];
len--;
}
bottom--;
for(int i=bottom;i>=top && len >= 1;i--){
res[index++] = matrix[i][left];
len--;
}
left++;
}
return res;
}
}
54.给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
和上一道题几乎一样,只不过返回的List集合
class Solution {
private List<Integer> list = new ArrayList();
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList();
int rows = matrix.length,columns = matrix[0].length;
int left= 0,right = columns-1,top = 0,bottom = rows - 1;
int numTotal = rows * columns;
while(numTotal >= 1){
for(int i=left;i<=right && numTotal >= 1;i++ ){
list.add(matrix[top][i]);
numTotal--;
}
top++;
for(int i=top;i<=bottom && numTotal >= 1;i++ ){
list.add(matrix[i][right]);
numTotal--;
}
right--;
for(int i=right;i>=left && numTotal >= 1;i-- ){
list.add(matrix[bottom][i]);
numTotal--;
}
bottom--;
for(int i=bottom;i>=top && numTotal >= 1;i-- ){
list.add(matrix[i][left]);
numTotal--;
}
left++;
}
return list;
}
}
59.给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
思路:因为输出的是一个n*n的矩阵,所以可以考虑用递归的方法,也是遵循上右下左的顺序进行矩阵填充。
class Solution {
private int count = 1;
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
matrix(res,0,n-1);
return res;
}
public void matrix(int[][] res,int x,int y){
if(x > y){
return;
}else if(x == y){
res[x][x] = count;
return;
}else{
for(int i=x;i<y;i++){
res[x][i] = count++;
}
for(int i=x;i<y;i++){
res[i][y] = count++;
}
for(int i=y;i>x;i--){
res[y][i] = count++;
}
for(int i=y;i>x;i--){
res[i][x] = count++;
}
}
matrix(res,x+1,y-1);
}
}