旋转图像
class Solution {
public void rotate(int[][] matrix) {
for(int i=0;i<matrix.length;i++){
for(int j=i+1;j<matrix[0].length;j++){
int temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}
}
for(int[] arr:matrix){
reverse(arr);
}
}
void reverse(int[] arr){
int i=0,j=arr.length-1;
while(i<j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
}
注意,j要从i开始 避免重复反转!
螺旋矩阵
先定义出四个边界点。按照上-右-下-左方式遍历,遍历完慢慢压缩,是左闭右闭区间
遍历哪条边,就压缩哪一条边,遍历上就往下压缩,遍历右就向左压缩
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m=matrix.length;
int n=matrix[0].length;
int tog=m*n;
int up=0,down=m-1,left=0,right=n-1;
List<Integer> res=new ArrayList<>();
while(res.size()<tog){
if(up<=down){
for(int j=left;j<=right;j++){
res.add(matrix[up][j]);
}
up++;
}
if(right>=left){
for(int i=up;i<=down;i++){
res.add(matrix[i][right]);
}
right--;
}
if(down>=up){
for(int j=right;j>=left;j--){
res.add(matrix[down][j]);
}
down--;
}
if(left<=right){
for(int i=down;i>=up;i--){
res.add(matrix[i][left]);
}
left++;
}
}
return res;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix=new int[n][n];
int left=0,right=n-1,up=0,down=n-1;
int count=1;//初始数
while(count<=n*n){
if(up<=down){
for(int j=left;j<=right;j++){
matrix[up][j]=count++;
}
up++;
}
if(right>=left){
for(int i=up;i<=down;i++){
matrix[i][right]=count++;
}
right--;
}
if(down>=up){
for(int j=right;j>=left;j--){
matrix[down][j]=count++;
}
down--;
}
if(left<=right){
for(int i=down;i>=up;i--){
matrix[i][left]=count++;
}
}
left++;
}
return matrix;
}
}