{
huixuan(8)
}
/// <summary>
/// 回旋函数
/// </summary>
/// <param name="n"></param>
public static void huixuan(int n)
{
int[,] result=new int[n,n]
int num = 1
int fx = 0
int cs = -1int cs1= -1int cs2 =-1int cs3 =-1
for (int i = 0i <n*ni++)
{
if (fx == 0)//向右
{
cs++
}
else if (fx== 1)//向下
{
cs1++
}
else if (fx == 2)//向左
{
cs2++
}
else if (fx == 3)//向上
{
cs3++
}
for (int j =0j <nj++)
{
if ( fx == 0)//向右
{
if (result[cs, j] != 0) continue
result[cs, j] = num++
}
else if (fx == 1)//向下
{
if (j + cs1 + 1 >= n) continue
if (result[j + cs1 + 1, n - cs1 - 1] != 0) continue
result[j + cs1 + 1, n - cs1 - 1] = num++
}
else if (fx == 2)//向左
{
if (n - j - cs2 >= n || n - j - cs2-1 <0) continue
if (result[n - cs2 - 1, n - j - cs2-1] != 0) continue
result[n - cs2 - 1, n - j - cs2-1] = num++
}
else if (fx == 3)//向上
{
if (n - j - cs3 >= n || n - j - cs3 <0) continue
if (result[n - j - cs3, cs3] != 0) continue
result[n - j - cs3, cs3] = num++
}
}
fx = fx+1 >3 ? 0 : fx+1
if (num == n * n+1)
break
}
for (int i = 0i <ni++)
{
for (int j = 0j <nj++)
{
Console.Write(result[i, j]+"\t")
}
Console.WriteLine("")
}
Console.Read()
}
//最呆板的实现方式,一行一行来实现public class HuiXuan {
public static void main(String[] args) {
new HuiXuan().huiX(8)
}
public void huiX(int num){
//按照二维数组的方式处理 行固定是3行
int[][] array = new int[3][num]
//第一行
for (int i = 0 i < num i++) {
array[0][i] = i+1
}
//最后一行
int index = 1
for (int i = num-1 i >=0 i--) {
array[2][i] = (num+1)+(index++)
}
//中间行
int midd = num*2+1
for (int i = 0 i < num-1 i++) {
array[1][i] = ++midd
}
array[1][num-1] = num+1
//循环打印
for (int i = 0 i < 3 i++) {
for (int j = 0 j < num j++) {
System.out.print(" "+array[i][j]+" ")
}
System.out.println()
}
}
}
实现结果如下
#include <stdio.h>int main()
{
int N,i,j,k,n,m,count=1
scanf("%d",&N)
int a[N][N]
if(N%2==0){
n=N/2
}else{
n=N/2+1
}
for(i=0i<ni++){
for(j=ij<N-ij++){
a[i][j]=count++
}
k=N-i-1
for(j=i+1j<N-ij++){
a[j][k]=count++
}
for(j=N-i-2j>=ij--){
a[k][j]=count++
}
for(j=N-i-2j>=i+1j--){
a[j][i]=count++
}
}
for(i=0i<Ni++){
for(j=0j<Nj++){
printf("%-3d",a[i][j])
}
printf("\n")
}
printf("\n")
return 0
}
运行结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)