题目54:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//给定矩阵,螺旋输出其所有元素
//思路:顺序为:右->下->左->上,每次走完一个方向,及时更新m或者n,就判断是否满足往下一个方向的行走
List<Integer> list=new ArrayList<>();
if(matrix.length==0){
return list;
}
int rowBegin=0,rowEnd=matrix.length-1;
int colBegin=0,colEnd=matrix[0].length-1;
//保证begin小于等于end
while(rowBegin<=rowEnd&&colBegin<=colEnd){
//右
for(int j=colBegin;j<=colEnd;j++){
list.add(matrix[rowBegin][j]);
}
//更新row
rowBegin++;
//下
for(int i=rowBegin;i<=rowEnd;i++){
list.add(matrix[i][colEnd]);
}
//更新col
colEnd--;
//判断是否有空间往回走
if(rowBegin<=rowEnd){
//左
for(int j=colEnd;j>=colBegin;j--){
list.add(matrix[rowEnd][j]);
}
}
//更新
rowEnd--;
//判断是否有空间往上走
if(colBegin<=colEnd){
for(int i=rowEnd;i>=rowBegin;i--){
list.add(matrix[i][colBegin]);
}
}
//更新
colBegin++;
}
return list;
}
}
题目(59):
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
分析:
class Solution {
public int[][] generateMatrix(int n) {
//类似sprial matrix给定矩阵,返回数据。该题给定数据,返回矩阵。
int [][] matrix=new int[n][n];
int rowBegin=0,rowEnd=n-1;
int colBegin=0,colEnd=n-1;
int count=1;
while(rowBegin<=rowEnd&&colBegin<=colEnd){
//右
for(int i=colBegin;i<=colEnd;i++){
matrix[rowBegin][i]=count;
count++;
}
rowBegin++;
//下
for(int i=rowBegin;i<=rowEnd;i++){
matrix[i][colEnd]=count;
count++;
}
colEnd--;
//左
if(rowBegin<=rowEnd){
for(int i=colEnd;i>=colBegin;i--){
matrix[rowEnd][i]=count;
count++;
}
}
rowEnd--;
//上
if(colBegin<=colEnd){
for(int i=rowEnd;i>=rowBegin;i--){
matrix[i][colBegin]=count;
count++;
}
}
colBegin++;
}
return matrix;
}
}