标签:循环调用 package 技术 png gen 复杂度 row ring hex
比方提供以下矩阵:
按照如下顺序打印出来:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
这道题直接写也没问题,就是特别容易出错,稍不留意就写错,而且这类题型我想要一种普适性的解法。
我想到的一种方法就是一圈一圈打印,从外到内,我们确定一个矩形,通常通过左上角的坐标和右下角的坐标即可,即(tR,tC)和(dR,dC),我们先写出打印一圈的方法,然后循环调用,如果我们发现左上角的坐标跑到了右下角坐标的右边或者下边,整个过程就停止,这样额外的空间复杂度是O(1)。No bibi,show me the code.
package com.darrenchan; /** * 转圈打印矩阵 * @author Think * */ public class SheXingPrint2 { public static void main(String[] args) { int[][] m = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; int tR = 0, tC = 0, dR = 0, dC = 3; while(tR <= dR && tC <= dC){ printEdge(m, tR++, tC++, dR--, dC--); } } public static void printEdge(int[][] m, int tR, int tC, int dR, int 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 curRow = tR; int curCol = tC; while(curCol != dC){ System.out.print(m[tR][curCol] + " "); curCol++; } while(curRow != dR){ System.out.print(m[curRow][dC] + " "); curRow++; } while(curCol != tC){ System.out.print(m[dR][curCol] + " "); curCol--; } while(curRow != tR){ System.out.print(m[curRow][tC] + " "); curRow--; } } } }
给出一个数字,比方是4,直接生成如下矩阵:
思路和上一个类似,只是稍微改一下即可:
package com.darrenchan; /** * 打印蛇形矩阵 * @author Think * */ public class SheXingPrint3 { public static int num = 1; public static void main(String[] args) { //给出多大的数字,就构造多大的矩阵 int[][] m = new int[4][4]; int tR = 0, tC = 0, dR = 3, dC = 3; while (tR <= dR && tC <= dC) { generateEdge(m, tR++, tC++, dR--, dC--); } for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { System.out.print(m[i][j] + "\t"); } System.out.println(); } } public static void generateEdge(int[][] m, int tR, int tC, int dR, int dC) { int curRow = tR; int curCol = tC; while(curCol != dC){ m[tR][curCol] = num; num++; curCol++; } while(curRow != dR){ m[curRow][dC] = num; num++; curRow++; } while(curCol != tC){ m[dR][curCol] = num; num++; curCol--; } while(curRow != tR){ m[curRow][tC] = num; num++; curRow--; } } }
标签:循环调用 package 技术 png gen 复杂度 row ring hex
原文地址:https://www.cnblogs.com/DarrenChan/p/8759077.html