题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:1 2 3 45 6 7 89 10 11 1213 14 15 16则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
分类:数组
解法1:思路要顺畅,我们观察一个次遍历,可以发现,每次都是从(i,i)这个坐标开始,例如起始坐标是(0,0),一圈下来,坐标是(1,1)
于是循环结束条件是i*2<cols
对于每圈,首先计算出结束的x,y坐标,用于边界判断
最后从左到右,从上到下,从右到左,从下到上,完成一圈
其中要注意,不是每次都能向下走,这里我使用了一个二维数组来简单判断某个元素是否被访问过
从而判断是否能继续走,当然还有更加高效的办法,只是这个方法比较简单,不用考虑很多情况
- import java.util.ArrayList;
- public class Solution {
- public ArrayList<Integer> printMatrix(int [][] matrix) {
- ArrayList<Integer> arr = new ArrayList<Integer>();
- int rows = matrix.length;
- int cols = matrix[0].length;
- boolean vis[][] = new boolean[rows][cols];
- int x = 0;
- while(x*2<cols && x*2<rows){
- int endX = rows-x-1;
- int endY = cols-x-1;
- for(int i=x;i<=endY;i++){
- if(!vis[x][i]){
- arr.add(matrix[x][i]);
- vis[x][i] = true;
- }
- }
- for(int i=x+1;i<=endX;i++){
- if(!vis[i][endY]){
- arr.add(matrix[i][endY]);
- vis[i][endY] = true;
- }
- }
- for(int i=endY-1;i>=x;i--){
- if(!vis[endX][i]){
- arr.add(matrix[endX][i]);
- vis[endX][i] = true;
- }
- }
- for(int i=endX-1;i>x;i--){
- if(!vis[i][x]){
- arr.add(matrix[i][x]);
- vis[i][x] = true;
- }
- }
- x = x + 1;
- }
- return arr;
- }
- }
解法2:优化每次过程,使用标志来记录每次的边界,包括left,top,right,bittom
- import java.util.ArrayList;
- public class Solution {
- public ArrayList<Integer> printMatrix(int [][] matrix) {
- ArrayList<Integer> res = new ArrayList<Integer>();
- int n = matrix.length;
- if(n==0) return res;
- int m = matrix[0].length;
- int x = 0,y = 0;
- int count = 0,limit = m*n;
- int right = m-1,bottom = n-1,left = 0,top = 0;
- while(count<limit){
- while(count<limit&&y<=right){res.add(matrix[x][y++]);count++;}
- y--;x++;top++;
- while (count<limit&&x<=bottom) {res.add(matrix[x++][y]);count++;}
- x--;y--;right--;
- while(count<limit&&y>=left) {res.add(matrix[x][y--]);count++;}
- x--;y++;bottom--;
- while(count<limit&&x>=top) {res.add(matrix[x--][y]);count++;}
- x++;y++;left++;
- }
- return res;
- }
- }
原文链接 http://blog.csdn.net/crazy__chen/article/details/44997845