import java.text.DecimalFormat;
/**
*
* @author: muyichun
* @date : 2016-3-14下午2:36:32
* @function:顺序打印方阵
*/
public class Main1 {
public static void main(String[] args) {
int rank = 3;
int count = rank - 1;
int index = 1;
int maxCell = rank * rank;
int arr[][] = new int[rank+1][rank+1];
int x = 1,y = 1;
while (true){
if (index > maxCell) break;
for (int i = 0; i < count; i++) {
if (index > maxCell) break;
arr[x][y++] = index++; //上面
}
for (int i = 0; i < count; i++) {
if (index > maxCell) break;
arr[x++][y] = index++; //右边
}
for (int i = 0; i < count; i++) {
if (index > maxCell) break;
arr[x][y--] = index++; //下边
}
for (int i = 0; i < count; i++) {
if (index > maxCell) break;
arr[x--][y] = index++; //左边
}
x++;y++;
if (count == 2) count--;
else count-=2; // 从外到内打印,每打印一层减一
}
for (int i = 1; i <= rank; i++){
for (int j = 1; j <= rank; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
输出结果:
1 2 3
8 9 4
7 6 5
——————————————————————————————————————————————————————————————————————————
public class Asist
{
/**
打印蛇形阵
Sample Input
5
Sample Output
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
*/
public static void main(String[] args)
{
int n = 5;
int nums[][] = new int[n][n];
int count = 1;
int x = n/2, y = n/2;
nums[x][y] = count++;
for (int i = 0; i < n / 2; i++)
{
// 右下
y++;
for (int j = 0; j < 2*(i+1); j++) nums[x++][y] = count++;
x--;
// 下
y--;
for (int j = 0; j < 2*(i+1); j++) nums[x][y--] = count++;
y++;
//左上
x--;
for (int j = 0; j < 2*(i+1); j++) nums[x--][y] = count++;
x++;
// 上
y++;
for (int j = 0; j < 2*(i+1); j++) nums[x][y++] = count++;
y--;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(nums[i][j] + "\t");
}
System.out.println();
}
}
}
输出结果:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13