面试题29:顺时针打印矩阵

2018-12-28  本文已影响0人  灰化肥发黑会挥发

题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字

public class printArray {
    public void printArrayOver(int[][] arr) {
        if(arr.length==0) return;
        int row = 0;
        int col = 0;
        boolean[][] visited = new boolean[arr.length+1][arr[0].length+1];
        for(int i=0;i<visited.length;i++){
            visited[i][0] = true;
            visited[i][visited.length-1]=true
        }
        for(int j=0;j<visited[0].length;j++){
            visited[0][j] = true;
            visited[visited.length-1][0]=true;
        }
        while(judge(arr,row,col)){
            if(judge(arr,startX,startY))
                right();
            if(judge(arr,startX,startY))
                down();
            if(judge(arr,startX,startY))
                left();
            if(judge(arr,startX,startY))
                up();
        }
    }
    public void left(){
        if(arr.length<=0) return;
        while(!visited[row+1][col+1]&&col<arr[0].length&&col>=0) {
            print(arr[row][col--]);
            visited[row+1][col+1] = true;
        }
    }
    public void right(){
        if(arr.length<=0) return;
        while(!visited[row+1][col+1]&&col<arr[0].length&&col>=0) {
            print(arr[row][col++]);
            visited[row+1][col+1] = true;
        }
    }
    public void down(){

        if(arr.length<=0) return;
        while(!visited[row+1][col+1]&&row<arr.length&&row>=0) {
            print(arr[row++][col]);
            visited[row+1][col+1] = true;
        }
    }
    public void up(){
        if(arr.length<=0) return;
        while(!visited[row+1][col+1]&&row<arr.length&&row>=0) {
            print(arr[row--][col]);
            visited[row+1][col+1] = true;
        }
    }
    public boolean judge(int[][] arr,int row,int col){
        boolean result = true;
        return visited[row-1][col]&&visited[row][col-1]&&visited[row+1][col]&&visited[row][col+1];
    }
}
上一篇下一篇

猜你喜欢

热点阅读