需求:根據二維數組值繪製圖形,0→空格,1→星號(*)
int[][] map = {
{0,0,0,1,0,0,0},
{0,0,1,0,1,0,0},
{0,1,0,0,0,1,0},
{1,0,0,0,0,0,1},
{0,1,0,0,0,1,0},
{0,0,1,0,1,0,0},
{0,0,0,1,0,0,0}
};
for (int row = 0; row < map.length; row++) {
for (int col = 0; col < map[row].length; col++) {
switch (map[row][col]) {
case 0: System.out.print(' '); break;
case 1: System.out.print('*'); break;
}
}
System.out.println(); // 換行
}
應用場景:遊戲地圖數據、俄羅斯方塊塊狀數據、像素圖渲染。體現**數據與邏輯分離**設計思想。
需求:生成 n×m 螺旋數組,數值從 1 遞增,順時針旋轉填充
4×4: 4×5:
1 2 3 4 1 2 3 4 5
12 13 14 5 14 15 16 17 6
11 16 15 6 13 20 19 18 7
10 9 8 7 12 11 10 9 8
int n = 4, m = 5;
int[][] data = new int[n][m];
int dire = 3; // 0上 1下 2左 3右
final int UP=0, DOWN=1, LEFT=2, RIGHT=3;
int value = 1, row = 0, col = 0;
data[0][0] = 1;
while (value < n * m) {
switch (dire) {
case UP: row--; if (row<0 || data[row][col]!=0) { row++; dire=RIGHT; continue; } break;
case DOWN: row++; if (row>=n || data[row][col]!=0) { row--; dire=LEFT; continue; } break;
case LEFT: col--; if (col<0 || data[row][col]!=0) { col++; dire=UP; continue; } break;
case RIGHT: col++; if (col>=m || data[row][col]!=0) { col--; dire=DOWN; continue; } break;
}
value++;
data[row][col] = value;
}
// 輸出右對齊
for (int i=0; i
此算法展示了多維數組下標靈活操控與複雜邊界條件處理的高級技巧。