19-顺时针打印矩阵
1. 题目描述
2. 题解
---------------------------------------------【2021-08-08】更新----------------------------------------------------------
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> res=new ArrayList<>();
ArrayList<Integer> tmp=new ArrayList<>();
if(matrix.length==0)
return tmp;
int top=0;//横坐标
int left=0;//纵
int bottom=matrix.length-1;//横
int right=matrix[0].length-1;//纵
while(true)
{
//left -> right
for(int j=left;j<=right;j++)
{
res.add(matrix[top][j]);
}
top++;
if(top>bottom)
break;//break跳出一层循环
//top -> bottom
for(int i=top;i<=bottom;i++)
{
res.add(matrix[i][right]);
}
right--;
if(right<left)
break;
//right -> left
for(int j=right;j>=left;j--)
{
res.add(matrix[bottom][j]);
}
bottom--;
if(bottom<top)
break;
//bottom -> top
for(int i=bottom;i>=top;i--)
{
res.add(matrix[i][left]);
}
left++;
if(left>right)
break;
}
return res;
}
}
查看23道真题和解析