顺时针打印矩阵
2013-11-13 16:14
246 查看
/** * 顺时针打印矩阵 * @author Q.Yuan * */ public class ClockwisePrintMatrix { public void printMatrix(int[][] a,int width,int height){ //起始打印坐标a[times][times],(0,0) (1,1) (2,2)...等 int times = 0; while(times <= width - 1 - times && times <= height - 1 - times ){ //最右边的列号 int colNum = width - 1 - times; //最下边的行号 int rowNum = height - 1 - times; //第一步 打印上边的行(一定会打印) for(int col = times;col <= colNum;col++){ System.out.print(a[times][col]+" "); } //第二步打印右边的列(两行以上才会打印) if(rowNum - times > 0){ for(int row = times + 1;row <= rowNum;row++){ System.out.print(a[row][colNum]+" "); } } //第三步打印下边的行(两列且两行以上才会打印) if(colNum - times + 1 >= 2 && rowNum - times + 1 >= 2){ for(int col = colNum - 1;col >= times;col--){ System.out.print(a[rowNum][col]+" "); } } //第四步打印左边的行(三行且两列以上) if(colNum - times + 1 >= 3 && rowNum - times + 1 >= 2){ for(int row = rowNum - 1;row >= times+1;row--){ System.out.print(a[row][times]+" "); } } System.out.println(); times ++ ; } } public static void main(String[] args) { ClockwisePrintMatrix cpm = new ClockwisePrintMatrix(); int [][] a = { { -1, -2, 3, -4 }, { -1, -2, 3, -4 }, { -1, -2, 3, -4 } }; cpm.printMatrix(a, a[0].length, a.length); } }
相关文章推荐
- 顺时针打印矩阵
- 矩阵------顺时针打印矩阵+顺时针旋转矩阵+之字形打印矩阵(Java)
- 剑指offer——顺时针打印矩阵
- 顺时针打印矩阵
- 剑指offer-题20:顺时针打印矩阵
- 剑指offer(20)顺时针打印矩阵
- 顺时针打印矩阵——20
- 《剑指Offer》之“顺时针打印矩阵”
- 剑指Offer-顺时针打印矩阵-C++-2ms-456k
- 顺时针打印矩阵
- 剑指offe:顺时针打印矩阵(最优解)——Array
- 程序员面试题精选100题(51)-顺时针打印矩阵
- 1,2,3…n*n 的数字按照顺时针螺旋的形式打印成矩阵(递归)
- 剑指offer题解C++【19】顺时针打印矩阵
- 顺时针打印矩阵
- 顺时针打印矩阵
- 剑指offer(16)-顺时针打印矩阵
- 顺时针打印矩阵
- 【Java笔试题】顺时针打印矩阵
- 顺时针打印矩阵