zoukankan      html  css  js  c++  java
  • 剑指:顺时针打印矩阵

    题目描述

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

    样例

    输入:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    
    输出:
    [1,2,3,4,8,12,11,10,9,5,6,7]

    解法:

     顺时针打印一圈,圈子越变越小,圈子变小一圈时,左上角坐标加一与右下角坐标减一。

    所以,利用这两个坐标(tR, tC)、(dR, dC)来缩小圈子。

    其中在一圈子中:

    先向右打印 curC -> dC

    再向下打印 curR -> dR

    再向左打印 curc -> tC

    再向上打印 cur -> tR

    当两坐标的行相等时(tR==dR),打印这一。

    当两坐标的列相等时(tC==dC),打印这一列。

    代码实现:

    package demo;
    
    public class Solution {
        
        public static void printMatrix(int[][] m){
            if(m==null || m.length<1) return;
            
            int tR = 0;
            int tC = 0;
            int dR = m.length-1;
            int dC = m[0].length-1;
            
            while(tR<=dR && tC<=dC){
                if(tR == dR){
                    for(int i=tC; i<=dC; i++)
                        System.out.print(m[tR][i]+" ");
                }else if(tC == dC){
                    for(int i=tR; i<=dR; i++)
                        System.out.print(m[i][tC]+" ");
                }else{
                    int curR = tR;
                    int curC = tC;
                    while(curC != dC){ //
                        System.out.print(m[tR][curC]+" ");
                        curC++;
                    }
                    while(curR != dR){
                        System.out.print(m[curR][dC]+" ");
                        curR++;
                    }
                    while(curC != tC){
                        System.out.print(m[dR][curC]+" ");
                        curC--;
                    }
                    while(curR != tR){
                        System.out.print(m[curR][tC]+" ");
                        curR--;
                    }
                }//end else
                tR++; tC++;
                dR--; dC--;
            }//endwhile
        }
    
    
        public static void main(String[] args) {
            int[][] matrix = { 
                    { 1, 2, 3, 4 }, 
                    { 5, 6, 7, 8 }, 
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } 
                    };
            printMatrix(matrix);
            
        }
    }
  • 相关阅读:
    常用的排序方法
    mongoose 操作
    formidable使用
    cors跨域(支持cookie跨域) node后台 express
    mongoose Schema写法
    vue生命周期钩子 (mounted 加载数据没有缓存用 activated 配合keep-alive组件)
    vue路由跳转 页面回到顶部
    RESTful风格的路由设计
    router-link 绑定事件不生效
    axios的Content-Type类型导致后台无法解析数据
  • 原文地址:https://www.cnblogs.com/lisen10/p/11188305.html
Copyright © 2011-2022 走看看