剑指offer面试题29(java版):顺时针打印矩阵

welcome to my blog

剑指offer面试题29(java版):顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.

第四次做; 核心: 1)使用四个边界的方式更好写 2)循环结束条件:边界的相对位置正确 3)left->right和top->down可以直接打印, 但是right->left需要在top<=down的情况下才能打印, top<=down说明还有有效的行没有打印, down->top需要在left<=right的情况下才能打印, left<=right说明还有有效的列
class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix==null || matrix.length==0 || matrix[0]==null || matrix[0].length==0)
            return new int[]{};
        //
        int n = matrix.length, m = matrix[0].length;
        int[] res = new int[n*m];
        int cur = 1, index=0;
        //打印的边界
        int top=0, down=n-1, left=0, right=m-1;
        while(top<=down && left<=right){
            //left -> right
            for(int j=left; j<=right; j++){
                res[index++] = matrix[top][j];
            }
            top++;
            
            //top -> down
            for(int i=top; i<=down; i++){
                res[index++] = matrix[i][right];
            }
            right--;
            
            //right -> left
            if(down >= top){
                for(int j=right; j>=left; j--){
                    res[index++] = matrix[down][j];
                }
            down--;
            }
            
            
            //down -> top
            if(left<=right){
                for(int i=down; i>=top; i--){
                    res[index++] = matrix[i][left];
                }
                left++;
            }
        }
        return res;
    }
}

思路

  • 主要是要弄清楚打印几圈, 去掉完整的一圈:rows-2, cols-2. (int)Math.min(Math.ceil(rows/2.0), Math.ceil(cols/2.0))
  • 因为矩阵的形状是任意的, 所以还要注意不完整的一圈, 比如说只有一行或者一列再或者一个数
  • 打印一圈的时候要格外注意边界的值是否需要打印,从而能够满足不是一圈的情况.
  • 上下左右四条边的边界打印情况, 上: 左闭右闭, 右: 上开下闭, 下: 右开左闭, 左:下开上开
  • 最重要的是上: 左闭右闭, 右: 上开下闭
  • 变量命名要有实际含义, 方便自己理解, 比如horizontalEnd, verticalEnd
  • horizontalEnd的取值由来: startXY - 0 = cols - 1 - horizontalEnd
  • verticalEnd的取值由来: startXY - 0 = rows - 1 - verticalEnd
第三次做, 核心: 1)圈数 2)打印起点; 注意一行一列的情况
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();
        if(matrix==null)
            return res;
        int rows = matrix.length, cols = matrix[0].length;
        int circleNum = (Math.min(rows,cols)+1)/2;
        for(int i=0; i<circleNum; i++){
            //左到右;左闭右闭
            for(int j=i; j<=cols-1-i; j++)
                res.add(matrix[i][j]);
            //上到下;上开下闭
            for(int j=i+1; j<=rows-1-i; j++)
                res.add(matrix[j][cols-1-i]);
            //右到左;右开左闭(只有构成圈的时候才打印; 最小的圈由四个点构成)
            if(cols-1-2*i>0 && rows-1-2*i>0)
                for(int j=cols-1-i-1; j>=i; j--)
                    res.add(matrix[rows-1-i][j]);
            //下到上;上开下开(只有构成圈的时候才打印)
            if(cols-1-2*i>0 && rows-1-2*i>0)
                for(int j=rows-1-i-1; j>i; j--)
                    res.add(matrix[j][i]);
        }
        return res;
    }
}
第二次做, 要注意的是:如何计算圈数; 每圈打印的起点(对角线元素);先算出矩阵的四个顶点; 圈数和打印起点的联系:第0圈的起点(0,0),第1圈的起点(1,1), 第二圈的起点(2,2); 如何用if控制打印
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> al = new ArrayList<Integer>();
        //input check
        if(matrix == null)
            return al;
        //
        int rows = matrix.length, cols = matrix[0].length;
        int circleNum = (int)Math.min(Math.ceil(rows/2.0), Math.ceil(cols/2.0));
        //明确圈数与打印起点的关系:第0圈的打印起点是(0,0), 第1圈的打印起点是(1,1), 第2圈的打印起点是(2,2)...以此类推
        for(int i=0; i<circleNum; i++){
            /*
            topLeft:(i,i)
            topRight:(i,cols - 1 - i)    i-0 = cols - 1 - y
            bottomLeft:(rows - 1 - i,i)   rows - 1 - x = i - 0
            bottomRight:(rows - 1 - i, cols - 1 - i)
            */
            //从左到右:左闭右闭;  这个是一定执行的, 下面的三个if可不一定执行了
            for(int j=i; j<=cols-1-i; j++)
                al.add(matrix[i][j]);
            //如果有高度,则从上到下:上开下闭
            if(rows-1-2*i > 0) //不满足if说明只有一行元素或一个元素
                for(int j=i+1; j<=rows-1-i; j++)
                    al.add(matrix[j][cols-1-i]);
            //如果同时有宽度和高度,则从右到左:右开左闭
            if(cols-1-2*i>0 && rows-1-2*i>0)//不满足if说明要么只有一列元素或者一行元素或者一个元素
                for(int j=cols-2-i; j>=i; j--)
                    al.add(matrix[rows-1-i][j]);
            //如果同时有宽度和高度,从下到上:下开上开
            if(cols-1-2*i>0 && rows-1-2*i>0)//不满足if说明要么只有一列元素或者一行元素或者一个元素
                for(int j=rows-2-i; j>i; j--)
                    al.add(matrix[j][i]);
        }
        return al;
    }
}
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        // input check
        
        // execute
        ArrayList<Integer> al = new ArrayList<Integer>();
        int rows = matrix.length;
        int cols = matrix[0].length;
        int circleNum = (int)Math.min(Math.ceil(rows/2.0), Math.ceil(cols/2.0));
        int startXY,horizontalEnd, verticalEnd;
        for(int i=0; i<circleNum; i++){
            startXY=i;
            horizontalEnd = cols-1-startXY;
            verticalEnd = rows-1-startXY;
            printCircle(matrix, startXY, horizontalEnd, verticalEnd, al); //传入起点
        }
        return al;
    }
    public void printCircle(int[][] matrix, int startXY, int horizontalEnd, int verticalEnd, ArrayList<Integer> al){
        // 从左到右打印
        for(int col=startXY; col<=horizontalEnd; col++) // 左闭右闭
            al.add(matrix[startXY][col]);
        
        if(startXY < verticalEnd) // 有高度
            for(int row=startXY+1; row<=verticalEnd; row++)// 从上到下打印. 注意起点终点,避免重复打印!!! 上开下闭
                al.add(matrix[row][horizontalEnd]);
        if(startXY < horizontalEnd && startXY < verticalEnd) //有宽度也要有高度  
            for(int col=horizontalEnd-1; col>=startXY; col--) // 从右到左打印  右开左闭
                al.add(matrix[verticalEnd][col]);
        if(startXY < horizontalEnd && startXY < verticalEnd) //有宽度也要有高度  下开上开
            for(int row=verticalEnd-1; row>startXY; row--)
                al.add(matrix[row][startXY]); // 从下到上打印
    }
}
逻辑更加清晰的代码(就是比较长)
import java.util.*;
 
public class Solution {
     
    public ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>() ;
        if(matrix==null || matrix.length==0) { return result ; }
 
        printMatrixClockWisely(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1, result);
 
        return result ;
    }
     
    public void printMatrixClockWisely(int[][] matrix, int startRow, int startCol, int endRow, int endCol, ArrayList<Integer> result) {
        if(startRow<endRow && startCol<endCol) { // 是个矩形
            for(int j=startCol; j<=endCol; j++) { result.add(matrix[startRow][j]) ; }   //Right
            for(int i=startRow+1; i<=endRow-1; i++) { result.add(matrix[i][endCol]) ; }     //Down
            for(int j=endCol; j>=startCol; j--) { result.add(matrix[endRow][j]) ; }     //Left
            for(int i=endRow-1; i>=startRow+1; i--) { result.add(matrix[i][startCol]) ; }   //Up
            printMatrixClockWisely(matrix, startRow + 1, startCol + 1, endRow - 1, endCol - 1, result) ;
        }else if(startRow==endRow && startCol<endCol) { // 只有一行
            for(int j=startCol; j<=endCol; j++) { result.add(matrix[startRow][j]) ; }
        }else if(startRow<endRow && startCol==endCol) { // 只有一列
            for(int i=startRow; i<=endRow; i++) { result.add(matrix[i][endCol]) ; }
        }else if(startRow==endRow && startCol==endCol) { // 只有一个元素
            result.add(matrix[startRow][startCol]) ;
        }else {
            return ;
        }
    }
     
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值