黑马程序员技术交流社区
标题:
两种截然不同的思考角度获取螺旋方阵
[打印本页]
作者:
清香白莲
时间:
2015-5-2 18:05
标题:
两种截然不同的思考角度获取螺旋方阵
import java.util.*;
public class Tmp
{
public static int[][] getScrewMatrix_1(int n)
{
int[][] a = new int[n][n];
int x = 1;
int i = 0;
int j = 0;
int d = 0;
while (x <= n * n)
{
switch(d)
{
case 0:
a[i][j++] = x++;
if (j == n || a[i][j] != 0)
{
--j;
++i;
d = (d + 1) % 4;
}
break;
case 1:
a[i++][j] = x++;
if (i == n || a[i][j] != 0)
{
--i;
--j;
d = (d + 1) % 4;
}
break;
case 2:
a[i][j--] = x++;
if (j == -1 || a[i][j] != 0)
{
++j;
--i;
d = (d + 1) % 4;
}
break;
case 3:
a[i--][j] = x++;
if (i == -1 || a[i][j] != 0)
{
++i;
++j;
d = (d + 1) % 4;
}
break;
}
}
return a;
}
public static int[][] getScrewMatrix_2(int n)
{
int[][] a = new int[n][n];
int x = 0;
for (int i = 0, j = 0; i < (n + 1) / 2; ++i, ++j)
{
while (j < n - 1 - i)
a[i][j++] = ++x;
while (i < j)
a[i++][j] = ++x;
while (j > n - 1 - i)
a[i][j--] = ++x;
while (i > j)
a[i--][j] = ++x;
}
if (n % 2 == 1)
a[n / 2][n / 2] = ++x;
return a;
}
public static void printScrewMatrix(int[][] a)
{
int bit = getNumLength(a.length * a.length) + 1;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
for (int k = 1; k <= bit - getNumLength(a[i][j]); k++)
System.out.print(" ");
System.out.print(a[i][j]);
}
System.out.println();
}
}
public static int getNumLength(int n)
{
int i = 0;
do
{
++i;
n /= 10;
} while (n != 0);
return i;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
printScrewMatrix(getScrewMatrix_1(sc.nextInt()));
printScrewMatrix(getScrewMatrix_2(sc.nextInt()));
sc.close();
}
}
复制代码
作者:
清香白莲
时间:
2015-5-2 18:07
从运行效率角度,两种方式是一样的。
从代码简洁角度,显然第二种方式更胜一筹。
作者:
空--格
时间:
2015-5-2 18:41
受益匪浅。。。。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2