本文目錄一覽:
java二維數組3*3螺旋矩陣實例,請解釋下循環的過程
public class T {
public static void main(String[] args) {
int i,j;
int[][] a = {{1,1,1},{2,2,2},{3,3,3}};
int[][] b = new int[3][3];
System.out.print(“初始矩陣:\n”);
for(i=0;i3;i++) {
for(j=0;j3;j++) {
System.out.print(a[i][j]+” “);
}
System.out.print(“\n”);
}
System.out.print(“轉置矩陣:\n”);
for(i=0;i3;i++) {
for(j=0;j3;j++) {
b[i][j] = a[j][i];
System.out.print(b[i][j]+” “);
}
System.out.print(“\n”);
}
}
}
java螺旋矩陣求助!
package cn.com.micc.javatwo; //根據實際情況修改
//蝸牛螺旋矩陣 請仔細研究矩陣階數變化時數據的遷移規律
//上一階矩陣會”整體”向右上或左下移動
public class AntiClockWiseArray {
public static int[][] getResult(int n) {
int[][] n1 = new int[1][1];
n1[0][0] = 1;
if (n == 1)
return n1;
int[][] result = new int[n][n];
int[][] temp = getResult(n – 1);
if (0 == (n – 1) % 2)
result = LeftDownMove(temp, n – 1); //n-1階矩陣向左下移動
else
result = RightUpMove(temp, n – 1); //n-1階矩陣向右上移動
return result;
}
public static int[][] LeftDownMove(int[][] in, int moment) {
int temp = moment * moment;
int nums = moment * 2 + 1;
int[][] out = new int[moment + 1][moment + 1];
//新矩陣補入上一階矩陣的值
for (int i = 0; i moment; ++i)
for (int j = 0; j moment; ++j)
out[i + 1][j] = in[i][j];
//兩個循環添加新矩陣新值
for (int k = 0; k moment + 1; ++k)
out[0][k] = temp + nums – k;
for (int l = 1; l moment + 1; ++l)
out[l][moment] = temp + nums – moment – l;
return out;
}
public static int[][] RightUpMove(int[][] in, int moment) {
int temp = moment * moment;
int nums = moment * 2 + 1;
int[][] out = new int[moment + 1][moment + 1];
//新矩陣補入上一階矩陣的值
for (int i = 0; i moment; ++i)
for (int j = 0; j moment; ++j)
out[i][j + 1] = in[i][j];
//兩個循環添加新矩陣新值
for (int k = 0; k moment + 1; ++k)
out[k][0] = temp + 1 + k;
for (int l = 1; l moment + 1; ++l)
out[moment][l] = temp + moment + 1 + l;
return out;
}
public static void printArray(int[][] temp, int n) {
//格式化打印矩陣
for(int i = 0; i n; ++i)
{
for(int j = 0; j n; ++j)
System.out.printf(“%5d”, temp[i][j]);
System.out.println();
}
}
public static void main(String[] args) {
printArray(getResult(6), 6); //輸入階數
}
}
output:
10階
82 81 80 79 78 77 76 75 74 73
83 50 49 48 47 46 45 44 43 72
84 51 26 25 24 23 22 21 42 71
85 52 27 10 9 8 7 20 41 70
86 53 28 11 2 1 6 19 40 69
87 54 29 12 3 4 5 18 39 68
88 55 30 13 14 15 16 17 38 67
89 56 31 32 33 34 35 36 37 66
90 57 58 59 60 61 62 63 64 65
91 92 93 94 95 96 97 98 99100
怎麼編寫JAVA螺旋矩陣?
按照你的要求用Java編寫的螺旋矩陣程序如下:
public class N {
public static void main(String[] args) {
final int N=4;
int a[][]=new int[N][N];
int num=1;
int i=0,j=0,m=0;
if(N%2==0)
m=N/2;
else
m=N/2+1;
for(i=0;i=m-1;i++){
for(j=i;j=N-i-1;j++){
a[i][j]=num;
num++;
}
for(j=i+1;j=N-i-1;j++) {
a[j][N-i-1]=num;
num++;
}
for(j=N-i-2;j=i;j–){
a[N-i-1][j]=num;
num++;
}
for(j=N-i-2;j=i+1;j–){
a[j][i]=num;
num++;
}
}
for(i=0;iN;i++){
for(j=0;jN;j++){
System.out.print(String.format(“%3d”,a[i][j]));
}
System.out.println();
}
}
}
運行結果:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/242832.html