顺时针打印矩阵
来源:互联网 发布:推广淘宝店 编辑:程序博客网 时间:2024/06/14 02:52
剑指offer有一道关于顺时针打印矩阵的面试题,感觉挺有意思的,题意很简单,输入一个矩阵,顺时针打印每个数字。
例如输入以下矩阵
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 。本体的关键是要把握好边界条件,每次从左上角的开始打印。
package sxd.learn.java.questions;public class PrintMatrix { private int r_upper_threshold; private int c_upper_threshold; private int r_lower_threshold; private int c_lower_threshold; public static void main(String[] args) { new PrintMatrix().run(); } public void run(){ int[][] matrix1 = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; int[][] matrix2 = { {1, 2, 3, 4}, {2, 3, 4, 5}, {5, 6, 7, 8}, }; int[][] matrix3 = { {1}, {2}, {3}, {4} }; int[][] matrix4 = { {1, 2}, {5, 6}, {3, 4}, {7, 8}, }; int[][] matrix5 = { {1, 2, 3, 4} }; printMatirxClockwisely(matrix5, 1, 4); } public void printMatirxClockwisely(int[][] matrix, int rows, int columns) { r_upper_threshold = rows; c_upper_threshold = columns; r_lower_threshold = -1; c_lower_threshold = -1; int startRows = 0; int startCols = 0; while (startRows < r_upper_threshold && startCols < c_upper_threshold) { printMatrixInCircle(matrix, startRows, startCols); r_lower_threshold++; c_lower_threshold++; r_upper_threshold--; c_upper_threshold--; startRows++; startCols++; } } private void printMatrixInCircle(int[][] matrix ,int r, int c){ while (c < c_upper_threshold){ System.out.print(matrix[r][c] + " "); c++; } c--; r++; while (r < r_upper_threshold) { System.out.print(matrix[r][c] + " "); r++; } r--; c--; while (c > c_lower_threshold && r != r_lower_threshold + 1) { System.out.print(matrix[r][c] + " "); c--; } c++; r--; while (r > r_lower_threshold + 1 && c != c_upper_threshold - 1) { System.out.print(matrix[r][c] + " "); r--; } }}
0 0
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 矩阵顺时针打印
- 顺时针打印矩阵
- 顺时针打印矩阵[算法]
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- C语言学习第一天
- Java --- 并发库concurrent包学习总结
- 2016.03.22(大水货啊 ,啥都不会)
- java详解单例模式
- Linux系统的休眠与唤醒简介
- 顺时针打印矩阵
- J2EE中MVC的使用以及优化
- Android新手入门2016(12)--基于Layout文件的AlertDialog
- 235. Lowest Common Ancestor of a Binary Search Tree
- module_init 和 late_initcall 区别
- Java程序与mysql的交互
- Mastering R plot -3笔记
- php设计模式学习系列(九)--桥接模式
- Android自定义view-弹出式dialog