算法1
(选定边界) $O(n)$
先确定本次旋转打印的左上角和右下角的坐标,然后将坐标穿入旋转打印函数,如果是只有一行,则tR==dR,如果只有一列,则tC==dC,如果都不是,则可旋转打印。
设定两个参数一个记录当前的行数,一个记录当前的列数,然后进行旋转,具体可见code
Java 代码
class Solution {
public int[] printMatrix(int[][] matrix) {
int[] arr2 = new int[0];
int len = matrix.length;
if(len==0)return arr2;
int tR = 0;
int tC = 0;
int dR = matrix.length-1;
int dC = matrix[0].length-1;
ArrayList<Integer> arr = new ArrayList<>();
while (tR<=dR && tC<=dC){
printEdge(matrix,tR++,tC++,dR--,dC--,arr);
}
Integer[] arr1 = arr.toArray(new Integer[arr.size()]);
arr2 = new int[arr1.length];
for (int i = 0; i < arr2.length ; i++) {
arr2[i] = arr1[i];
}
return arr2;
}
private void printEdge(int[][] matrix, int tR, int tC, int dR, int dC,ArrayList arr) {
if(tR==dR){
for (int i = tC; i <= dC; i++) {
arr.add(matrix[tR][i]);
}
}else if(tC==dC){
for (int i = tR; i <=dR ; i++) {
arr.add(matrix[i][tC]);
}
}else{
int curC = tC;
int curR = tR;
while (curC!=dC){
arr.add(matrix[tR][curC]);
curC++;
}
while (curR!=dR){
arr.add(matrix[curR][dC]);
curR++;
}
while (curC!=tC){
arr.add(matrix[dR][curC]);
curC--;
}
while (curR!=tR){
arr.add(matrix[curR][tC]);
curR--;
}
}
}
}