螺旋矩陣演算法

來源:互聯網
上載者:User

標籤:style   cti   演算法   for   io   new   

//螺旋輸出1-25
public class Sequence {
public static void main(String[] args) {
int n = 5;
// 0:向右,1:向下,2:向左,3:向上
int direction = 0;
// 行,列
int row = 0, col = 0;
int num = 0;

int[] array = new int[n * n];
while (array[row * n + col] == 0) {
num++;
array[row * n + col] = num;
switch (direction) {
case 0:
col++;
break;
case 1:
row++;
break;
case 2:
col--;
break;
case 3:
row--;
break;
}
if (row == n || col == n || row == -1 || col == -1
|| array[row * n + col] != 0) {
direction++;
if (direction == 4)
direction = 0;
switch (direction) {
case 0:
row++;
col++;
break;
case 1:
row++;
col--;
break;
case 2:
row--;
col--;
break;
case 3:
row--;
col++;
break;
}
}
}

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%-3s", array[i * n + j]);
}
System.out.println();
}
}

}

-----------------------------------------------------------

//矩陣轉換
public class TestArray {
public static void main(String[] args) {
int array[][] = { { 22, 18, 36 }, { 27, 34, 58 }, { 12, 51, 32 },
{ 14, 52, 64 } };// 建立一個4行3列的二維數組
int brray[][] = new int[3][4];// 建立一個3行4列的數組,用於接收轉置後的矩陣
System.out.println("原型矩陣如下:");
for (int i = 0; i < array.length; i++) {// 遍曆array數組中的元素
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < array.length; i++) {// 此時的i是array數組的行,brray的列
for (int j = 0; j < brray.length; j++) {// 此時的j是array數組的列,brray的行
brray[j][i] = array[i][j];// 將array數組中的第i行j列的元素賦給brray數組中的j行i列
}
}
System.out.println("\n轉置後的矩陣如下:");
for (int i = 0; i < brray.length; i++) {// 遍曆轉置後brray數組中的元素
for (int j = 0; j < brray[i].length; j++) {
System.out.print(brray[i][j] + " ");
}
System.out.println();
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.