java数字顺时针螺旋矩阵
从键盘输入一个整数(1~20)
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
这个程序怎么写呀?请各位帮忙写一下!
------解决方案--------------------
import java.io.BufferedReader;
import
java.io.IOException;
import java.io.InputStreamReader;
public class BBB {
public static int d;
public static void main(String[] args) {
BBB l=new BBB();
System.out.println("请输入一个数:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String str = br.readLine();
d= Integer.parseInt(str);
} catch (
NumberFormatException e) {
e.printStackTrace();
} catch (
IOException e) {
e.printStackTrace();
}
int [][]a=new int [d][d];
System.out.println("排列:");
int n=0;
boolean flay=true;
while(flay&&n<d)
{
for(int i=n;i<d-n;i++)
if(n==0)
a[n][i]=i+1;
else
a[n][i]=a[n][i-1]+1;
flay=l.Chu(a);
if(flay==false) break;
for(int i=n;i<d-n-1;i++)
if(n==0)
a[i+1][d-1-n]=i+d+1;
else
a[i+1][d-1-n]=a[i][d-1-n]+1;
for(int i=n;i<d-n-1;i++)
if(n==0)
a[d-1-n][i]=a[d-1-n][d-1-n]+d-1-i;
else
a[d-1-n][i]=a[d-1-n][d-1-n]+d-1-n-i;
flay=l.Chu(a);
if(flay==false) break;
for(int i=1+n;i<d-n-1;i++)
if(n==0)
a[i][n]=a[d-1-n][n]+d-1-i;
else
a[i][n]=a[d-1-n][n]+d-1-i-n;
flay=l.Chu(a);
n++;
}
l.OUT(a);
}
public void OUT(int [] []a)
{
for(int i=0;i<d;i++)
{
for(int j=0;j<d;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
public boolean Chu(int [] []a)
{
for(int i=0;i<d;i++)
{
for(int j=0;j<d;j++)
{
if(a[i][j]==0)
return true;
}
}
return false;
}
}
------解决方案--------------------
Java code
package test;
public class Test {
public static void main(String[] args) {
final int count = 10;
final int max = count * count;
int[][] data = new int[count][count];
int x = -1, y = 0, cur = 0;
while (cur < max) {
for (; x + 1 < count && data[x + 1][y] == 0; data[y][++x] = ++cur);
for (; y + 1 < count && data[x][y + 1] == 0; data[++y][x] = ++cur);
for (; x - 1 >= 0 && data[y][x - 1] == 0; data[y][--x] = ++cur);
for (; y - 1 >= 0 && data[y - 1][x] == 0; data[--y][x] = ++cur);
}
for (int i = 0; i < count; ++i) {
for (int j = 0; j < data[i].length; ++j) {
System.out.printf("%-3d ", data[i][j]);
}
System.out.println();
}
}
}