二位数组 顺时针打印矩阵
输入一个数字n,顺时针生成一个n阶矩阵。
比如输入n = 5,生成矩阵如下
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
该题只要考虑比较好的办法是从外到内一圈一圈的打印,就如下图所示:
在按圈进行生成的时候需要考虑到两个坐标和截至条件,左上角(tr,tc),右下角(dr,dc),以及循环的截至条件
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = 2;
int[][] arr = new int[n][n];
int begin = 0;//tr和tc相等,就用一个数字代替
int end = n - 1;
int num = 0;
while (begin <= end) {
num = getArray(arr, begin, end, num);
begin++;
end--;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
public static int getArray(int[][] arr, int begin, int end, int num) {
if (begin == end) {
arr[begin][end] = ++num;
} else {
int curR = begin;
int curC = begin;
while (curC < end)
arr[begin][curC++] = ++num;
while (curR < end)
arr[curR++][end] = ++num;
while (curC > begin)
arr[end][curC--] = ++num;
while (curR > begin)
arr[curR--][begin] = ++num;
}
return num;
}
}
题目二:矩阵安装对角线可以划分为上三角和下三角,现在输入一个数字,在n阶矩阵的上三角中顺时针填充数字
解题思路,和上面的思路一样,也是从外到内,一圈一圈的生成
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int tl = 0;
int dr = n - 1;
int num = 0;
int[][] arr = new int[n][n];
while (tl < n / 2) {
if (tl == dr)
arr[tl][dr] = ++num;
int row = tl;
int col = tl;
while (col < dr) {
arr[row][col++] = ++num;
}
while (row < dr && col > tl) {
arr[row++][col--] = ++num;
}
while (row > tl) {
arr[row--][col] = ++num;
}
tl++;
dr -= 2;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
System.out.println(arr[i][j]);
}
}
}
}