剑指offer 第十九题 顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int m =matrix[0].length;  //列数
        int n =matrix.length;     //行数
        if(m ==0 || n==0)
            return null;
        ArrayList<Integer> result =new ArrayList<Integer>();
        int direction =0;
        //0为向右,1位向下,2为向左,3为向上。依次循环。
        int size =0;
        int i=0; //n
        int j=0;//m
        int[][] tag =new int[n][m];
        while(size <m*n){
            result.add(matrix[i][j]);
            tag[i][j] =1;
            size++;
            if(direction ==0){
                //if(j ==m-1)
                if(j<m-1 && tag[i][j+1]==0){
                    j++;
                }
                else {
                    direction =(direction+1)%4;
                    i++;
                }
 
            }else if(direction ==1){
                if(i<n-1 && tag[i+1][j] ==0){
                    i++;
                }else {
                    direction =(direction+1)%4;
                    j--;
                }
 
            }else if(direction ==2){
                if(j>0 && tag[i][j-1] == 0){
                    j--;
                }else {
                    direction =(direction+1)%4;
                    i--;
                }
 
            }else if(direction ==3){
                if(i>0 && tag[i-1][j]==0){
                    i--;
                }else {
                    direction =(direction+1)%4;
                    j++;
                }
 
            }
        }
 
        //System.out.println(result.isEmpty());
        return result;
        
    }
}

 

上一篇:Pycharm 社区版安装Django


下一篇:flex弹性盒子实现微博页面