面试题29:顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
思路:
- 定义四个边界 startX = 0、endX = arr.length、startY = 0、endY = arr[0].length
- 首先从左往右走,走完后 startX++
- 然后从上往下走,走完后 endY–
- 然后从右往左走,走完后 endX–
- 最后从下往上走,走完后 startX++
- 每次 startX、endX、startY、endY变化,都要判断一下,startX 有没有超过 endX,startY 有没有超过 endY,如果有,遍历结束!
代码实现:
package Question29;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class T01 {
public static void main(String[] args) {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
System.out.println(Arrays.toString(solve(arr)));
}
public static int[] solve(int[][] arr) {
if(arr == null || arr.length == 0) return null;
int[] result = new int[arr.length * arr[0].length];
int index = 0;
int startX = 0, endX = arr.length-1;
int startY = 0, endY = arr[0].length-1;
while(startX <= endX && startY <= endY) {
//从左到右遍历
for(int j = startY; j <= endY; j++) result[index++] = arr[startX][j];
if(++startX > endX) break;
//从上到下遍历
for(int i = startX; i <= endX; i++) result[index++] = arr[i][endY];
if(startY > --endY) break;
//从左到右遍历
for(int j = endY; j >= startY; j--) result[index++] = arr[endX][j];
if(startX > --endX) break;
//从下到上遍历
for(int i = endX; i >= startX; i--) result[index++] = arr[i][startY];
if( ++startY > endY) break;
}
return result;
}
}