当前位置:编程学习 > C#/ASP.NET >>

求大师给答案,电脑老师说不懂 大学数学老师说不会

由用户输入一个整数(>=1),则形成一个顺时针螺旋递减等差数列矩阵,

符合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
--------------------编程问答-------------------- 找到规律就是一个循环嘛 --------------------编程问答-------------------- 数学问题,队列。 --------------------编程问答-------------------- 顺时针螺旋递减等差数列矩阵,你看看你自己给出的符合吗?或许我没看懂你的顺时针的轨迹是怎么转的。 --------------------编程问答-------------------- 我这数学水平是不行了 --------------------编程问答--------------------
引用 3 楼 xiongxyt2 的回复:
顺时针螺旋递减等差数列矩阵,你看看你自己给出的符合吗?或许我没看懂你的顺时针的轨迹是怎么转的。

楼主写的没错啊 --------------------编程问答-------------------- 方法很多。最直观的就是直接控制2维数组的下标。 --------------------编程问答--------------------
引用 3 楼 xiongxyt2 的回复:
顺时针螺旋递减等差数列矩阵,你看看你自己给出的符合吗?或许我没看懂你的顺时针的轨迹是怎么转的。


题目都看不懂 唉 真不想骂人 --------------------编程问答--------------------
引用 6 楼 wuyazhe 的回复:
方法很多。最直观的就是直接控制2维数组的下标。

说的轻松 你试试?? --------------------编程问答--------------------
引用 8 楼 iisahandsomeboy 的回复:
引用 6 楼 wuyazhe 的回复:
方法很多。最直观的就是直接控制2维数组的下标。

说的轻松 你试试??

那就是个半桶水,想想 的确很难。 --------------------编程问答-------------------- 还真有点麻烦,不过还有点意思

        class Point
        {
            public int X;
            public int Y;

            public Point Offset(Point p)
            {
                Point pRet = new Point(X, Y);
                pRet.X += p.X;
                pRet.Y += p.Y;
                return pRet;
            }
            public Point(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
        }

        static void Main(string[] args)
        {
            int num = int.Parse(Console.ReadLine());
            int[,] matrix = new int[num, num];
            for (int i = 0; i < num; i++)
                for (int j = 0; j < num; j++)
                    matrix[i, j] = 0;

            List<Point> direction = new List<Point>();
            direction.Add(new Point(0, 1));
            direction.Add(new Point(1, 0));
            direction.Add(new Point(0, -1));
            direction.Add(new Point(-1, 0));

            Point point = new Point(0, 0);
            for (int i = 0; i < num * num; i++)
            {
                matrix[point.X, point.Y] = i + 1;
                bool found = false;
                for (int j = 0; j < 4; j++)
                {
                    Point offset = direction[0];
                    Point temp = point.Offset(offset);
                    if (temp.X >= 0 && temp.X < num && temp.Y >= 0 && temp.Y < num && matrix[temp.X, temp.Y] == 0)
                    {
                        found = true;
                        point = temp;
                        break;
                    }
                    direction.RemoveAt(0);
                    direction.Add(offset);
                }
                if (!found)
                    break;
            }
            for (int i = 0; i < num; i++)
            {
                for (int j = 0; j < num; j++)
                {
                    Console.Write(matrix[i, j].ToString().PadLeft(4));
                }
                Console.WriteLine();
            }
        }
--------------------编程问答-------------------- 1   2  3 4
12 13 14 5
11 16 15 6
10  9  8 7

1   2  3  4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

1   2  3  4  5  6
20 21 22 23 24  7
19 32 33 34 25  8
18 31 36 35 26  9
17 30 29 28 27 10
16 15 14 13 12 11  
--------------------------------------

1   2  3  4  5  6
20              7
19              8
18              9
17             10
16 15 14 13 12 11  

21 22 23 24  
32       25  
31       26  
30 29 28 27

33 34 
36 35

 
--------------------编程问答--------------------
    class Program
    {
        static void Main(string[] args)
        {
            int num = int.Parse(Console.ReadLine());
            int [][]a = new int[num][];
            for (int i = 0; i < num; i++)
            {
               a[i] = new int[num];
            }

            for (int i = 0; i < num; i++)
            {
                for (int j = 0; j < num; j++)
                {
                    a[i][j] = 0;
                }
            }

            Output(num, 0, 1, a);

            for (int i = 0; i < num; i++)
            {
                for (int j = 0; j < num; j++)
                {
                    Console.Write(a[i][j].ToString() + " ");
                }
                Console.Write("\r\n");
            }
        }

        static void Output(int n, int line, int startNum, int [][]a)
        {
            if (line > (n-1)/2)
            {
                return;
            }
            for (int i = line; i < n - line; i++)
            {
                a[line][i] = startNum;
                startNum++;
            }
            for (int i = line + 1; i < n - line; i++)
            {
                a[i][n-line-1] = startNum;
                startNum++;
            }
            for (int i = n - line - 2; i > line - 1; i--)
            {
                a[n-line-1][i] = startNum;
                startNum++;
            }
            for (int i = n - line - 2; i > line; i--)
            {
                a[i][line] = startNum;
                startNum++;
            }

            Output(n, line + 1, startNum, a);
        }
    }


随手写了个,感觉还是蛮简单的 --------------------编程问答--------------------
引用 10 楼 icedmilk 的回复:
还真有点麻烦,不过还有点意思
C# code

        class Point
        {
            public int X;
            public int Y;

            public Point Offset(Point p)
            {
                Point pRet = new Po……
正解! --------------------编程问答-------------------- --------------------编程问答-------------------- --------------------编程问答-------------------- 就喜欢这种东西,可以打发时间

static void Main(string[] args)
        {
            do
            {
                Console.Write("请输入一个整数(>=1):");
                int n = 0;
                Int32.TryParse(Console.ReadLine(), out n);
                if (n < 1)
                    return;
                int[,] result = new int[n, n];
                SetValue(ref result, 0, n, 1);
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        Console.Write(string.Format("{0,3}", result[i, j]));
                        if (j == n - 1)
                        {
                            Console.WriteLine();
                        }
                    }
                }
                Console.WriteLine("按任意键继续,按ESC可退出");
                ConsoleKeyInfo cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Escape) break;
            } while (true);
            Console.ReadLine();
        }
static void SetValue(ref int[,] result, int start, int end, int startvalue)
        {
            if (start == end - 1)
            {
                result[start, start] = startvalue;
            }
            else
            {
                for (int i = start; i < end; i++)
                {
                    result[start, i] = startvalue++;
                }
                for (int i = start + 1; i < end; i++)
                {
                    result[i, end-1] = startvalue++;
                }
                for (int i = end - 2; i >= start; i--)
                {
                    result[end - 1, i] = startvalue++;
                }
                for (int i = end - 2; i >= start + 1; i--)
                {
                    result[i, start] = startvalue++;
                }
            }
            
            start++;
            end--;
            if(end>=start)
            {
                SetValue(ref result,start,end,startvalue);
            }
            
        }
--------------------编程问答-------------------- --------------------编程问答-------------------- 混分


int param = 9;

int num = param;
int[,] nums = new int[num, num];
int x=0, y = 0;
int direction = 0;//0:→; 1:↓; 2:←; 3:↑;
for (int i = 1; i <= param * param; i++)
{
    nums[x, y] = i;

    switch (direction)
    {
        case 0:
            y++;
            if (y >= num)
            {
                direction = ++direction % 4;
                y--;
                x++;
            }
            break;
        case 1:
            x++;
            if (x >= num)
            {
                direction = ++direction % 4;
                x--;
                y--;
            }
            break;
        case 2:
            y--;
            if (y < param - num)
            {
                direction = ++direction % 4;
                y++;
                x--;
                num--;
            }
            break;
        case 3:
            x--;
            if (x < param - num)
            {
                direction = ++direction % 4;
                x++;
                y++;
            }
            break;
    }
}

for (int i = 0; i < param; i++)
{
    for (int j = 0; j < param; j++)
    {
        Console.Write("{0,4}", nums[i, j]);
    }
    Console.WriteLine();
}
--------------------编程问答-------------------- 规律还是挺容易理解的,不算特别复杂吧 --------------------编程问答-------------------- 这题以前做过 给大家看看
#include<stdio.h>
int jisuan(int i,int j,int n);//计算ij对应数所在的圈数
void main()
{
 int i,j,circle,n,sign[100];
 printf("请输入矩阵的阶:");
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
  sign[i]=1;
 }//标记数组初始化为“0”
 for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
   circle=jisuan(i,j,n);
   if(i!=circle&&(n+1-i)!=circle)
   {
    if(j==circle) printf("%3d ",(2-i+circle-1)+(4*(n-1)*circle-4*circle*(circle-1)));
    else printf("%3d ",-(2-i+circle-1)+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1))+(n-2*(circle-1)+1));
   }
   else 
   {
    if(i==circle) printf("%3d ",(j-circle+1)+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1)));
    else printf("%3d ",(-2-j+circle)+3*(n-2*(circle-1))+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1)));
   }
   //sign[circle-1]++;
  }
  printf("\n");
 }//函数主体
}

int jisuan(int i,int j,int n)
{
if(i>n/2) i=n+1-i;
if(j>n/2) j=n+1-j;
if(j>=i) return i;
else return j;
}  

//sign[circle-1]+(4*(n-1)*(circle-1)+2*(circle-1)*(circle-2))) --------------------编程问答-------------------- for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
  circle=jisuan(i,j,n);
  if(i!=circle&&(n+1-i)!=circle)
  {
  if(j==circle) printf("%3d ",(2-i+circle-1)+(4*(n-1)*circle-4*circle*(circle-1)));
  else printf("%3d ",-(2-i+circle-1)+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1))+(n-2*(circle-1)+1));
  }
  else  
  {
  if(i==circle) printf("%3d ",(j-circle+1)+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1)));
  else printf("%3d ",(-2-j+circle)+3*(n-2*(circle-1))+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1)));
  }
  //sign[circle-1]++;
  }
  printf("\n");
不是很理解啊,www.37tk.com --------------------编程问答--------------------
引用 21 楼 chenguang1228 的回复:
for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
  circle=jisuan(i,j,n);
  if(i!=circle&&(n+1-i)!=circle)
  {
  if(j==circle) printf("%3d ",(2-i+circle-1)+(4*(n-1)*circle-4*circle*(circle-1……

这是我以前做的 看了一下午 才找到规律 现在说实话 我也想不起来了
http://student.csdn.net/space.php?uid=129463&do=blog&id=16168
从我以前写的博客里面粘来的
--------------------编程问答--------------------
引用 21 楼 chenguang1228 的回复:
for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
  circle=jisuan(i,j,n);
  if(i!=circle&&(n+1-i)!=circle)
  {
  if(j==circle) printf("%3d ",(2-i+circle-1)+(4*(n-1)*circle-4*circle*(circle-1……

大致说一下吧
关键代码是两层for循环
第一个for是控制的列 第二个是控制的行
 circle=jisuan(i,j,n);
这句计算机要打印的字符在哪一圈 因为下面的if else要用到这个变量
下面的几条语句就是我找到的规律了  
if(i!=circle&&(n+1-i)!=circle)
  {
  if(j==circle) printf("%3d ",(2-i+circle-1)+(4*(n-1)*circle-4*circle*(circle-1)));
  else printf("%3d ",-(2-i+circle-1)+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1))+(n-2*(circle-1)+1));
  }
  else   
  {
  if(i==circle) printf("%3d ",(j-circle+1)+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1)));
  else printf("%3d ",(-2-j+circle)+3*(n-2*(circle-1))+(4*(n-1)*(circle-1)-4*(circle-2)*(circle-1)));
  }
仔细看看 其实就是根据circle i j 等变量 计算将要打印的字符是什么 --------------------编程问答--------------------
引用 10 楼 icedmilk 的回复:
还真有点麻烦,不过还有点意思

C# code

        class Point
        {
            public int X;
            public int Y;

            public Point Offset(Point p)
            {
                Point pRet……


这哥们实力很强 --------------------编程问答-------------------- 应该不难 学习下 呵呵
--------------------编程问答-------------------- --------------------编程问答-------------------- 首先是考数学逻辑,数学逻辑好了,代码问题就不会很大。 --------------------编程问答-------------------- 用vb写了一个,也贴出来吧

Private Sub Command1_Click()
    Dim i       As Long
    Dim n       As Long
    Dim a()     As Long
    Dim tmp     As Long
    Dim j       As Long         '行上边界
    Dim k       As Long         '列上边界
    Dim l       As Long         '行下边界
    Dim m       As Long         '列下边界
    Dim flag    As Integer      '0,1,2,3 表示填充方向 左->右 上->下 右->左 下->上
    Dim str     As String
    
    n = Text1   '输入参数,整数
    ReDim a(n, n) As Long
    j = 1
    k = 1
    l = n
    m = n
    flag = 0
    tmp = 1
    
    For i = 1 To n * n
        Select Case flag
            Case 0
                a(j, tmp) = i
                tmp = tmp + 1
                
                If tmp > m Then
                    j = j + 1
                    flag = 1
                    tmp = j
                End If
            Case 1
                a(tmp, m) = i
                tmp = tmp + 1
                
                If tmp > l Then
                    m = m - 1
                    flag = 2
                    tmp = m
                End If
            Case 2
                a(l, tmp) = i
                tmp = tmp - 1
                
                If tmp < k Then
                    l = l - 1
                    flag = 3
                    tmp = l
                End If
            Case 3
                a(tmp, k) = i
                tmp = tmp - 1
                
                If tmp < j Then
                    k = k + 1
                    flag = 0
                    tmp = k
                End If
        End Select
    Next
    
    For i = 1 To n
        str = ""
        
        For j = 1 To n
            str = str & a(i, j) & " "
        Next
        
        Debug.Print str & vbCrLf
    Next
End Sub
--------------------编程问答-------------------- 都是高人呐! --------------------编程问答-------------------- 在C版见过类似的,只不过那时我做的是从中间向外转,你这是从前面就转了,很容易! --------------------编程问答-------------------- 麻烦,旋得我都混了

public class Test000 {

public static void main(String [] args){
int i=1;
int num=6;
int row=1;//方向
int rowNum=0;//下标
int rowMax=num-1;
int rowMin=0;
int col=1;//方向
int colNum=0;//下标
int colMax=num-1;
int colMin=0;
int [][] s=new int [num][num];
int isRow=0;
int isCol=1;
while(i<=num*num){
//行运算
if(isCol==1){
s[rowNum][colNum]=i++;
if(colNum+col>colMax||colNum+col<colMin){
isRow=1;
isCol=0;
if(col>0){
rowMin=rowMin+1;
}else{
rowMax=rowMax-1;
}
col=col*(-1);
rowNum=rowNum+row;
continue;
}else{
colNum=colNum+col;
}

}
//列运算
if(isRow==1){
s[rowNum][colNum]=i++;
if(rowNum+row>rowMax||rowNum+row<rowMin){
isRow=0;
isCol=1;
if(row>0){
colMax=colMax-1;
}else{
colMin=colMin+1;
}
row=row*(-1);
colNum=colNum+col;
continue;
}else{
rowNum=rowNum+row;
}

}

}

for(int m=0;m<s.length;m++){
for(int n=0;n<s[0].length;n++){
System.out.print(s[m][n]+" ");
}
System.out.println();
}

}

}



1 2 3 4 5 6 
20 21 22 23 24 7 
19 32 33 34 25 8 
18 31 36 35 26 9 
17 30 29 28 27 10 
16 15 14 13 12 11 
--------------------编程问答-------------------- 就是一圈圈向里面递增或递减吧,0号位和中间位最大祸最小。找到规律就好做了,楼主是在显示屏后面看的吗(顺顺时针递减,中心出发) --------------------编程问答-------------------- 都是N人啊, --------------------编程问答-------------------- --------------------编程问答-------------------- 用VB来实现,牛X.... --------------------编程问答-------------------- 这个很简单 不需要多少行代码就可以 我现在没时间写 一会儿贴上 --------------------编程问答--------------------

    Dim a(,) As Integer
    Enum FillDirect
        RIGHT = 1
        LEFT = 2
        UP = 3
        DOWN = 4
    End Enum
    Structure arrayFillState
        Dim n As Integer
        Dim row As Integer
        Dim col As Integer
        Dim Direct As FillDirect
    End Structure

    Function Fill(ByVal fs As arrayFillState, ByVal n As Integer) As arrayFillState
        Dim fs1 As arrayFillState = fs
        With fs1
            Select Case fs1.Direct
                Case FillDirect.LEFT
                    For i As Integer = fs1.col To n - 1
                        If a(.row, i) = 0 Then
                            a(.row, i) = .n
                            .n += 1
                            If i = n - 1 Then
                                .Direct = FillDirect.DOWN
                                .col = n - 1
                                .row = 1
                            End If
                        Else
                            .Direct = FillDirect.DOWN
                            .col = i - 1
                            .row += 1
                            Exit For
                        End If
                    Next
                Case FillDirect.DOWN
                    For i As Integer = .row To n - 1
                        If a(i, .col) = 0 Then

                            a(i, .col) = .n
                            .n += 1
                            If i = n - 1 Then
                                .row = n - 1
                                .col = n - 2
                                .Direct = FillDirect.RIGHT


                            End If

                        Else
                            .row = i - 1
                            .col -= 1
                            .Direct = FillDirect.RIGHT
                            Exit For
                        End If
                    Next
                Case FillDirect.RIGHT
                    For i As Integer = .col To 0 Step -1
                        If a(.row, i) = 0 Then
                            a(.row, i) = .n
                            .n += 1
                            If i = 0 Then
                                .col = 0
                                .row = n - 2
                                .Direct = FillDirect.UP

                            End If
                        Else
                            .col = i + 1
                            .row -= 1
                            .Direct = FillDirect.UP

                            Exit For
                        End If
                    Next
                Case FillDirect.UP
                    For i As Integer = .row To 0 Step -1
                        If a(i, .col) = 0 Then
                            a(i, .col) = .n
                            .n += 1
                        Else
                            .row = i + 1
                            .col += 1
                            .Direct = FillDirect.LEFT
                            Exit For
                        End If
                    Next
            End Select

            If .n < n * n Then
                Return Fill(fs1, n)
            Else
                a(.row, .col) = n * n
                Return fs1
            End If
        End With
    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim n As Integer = 9
        ReDim a(n, n)

        Dim fs As arrayFillState
        With fs
            .row = 0
            .col = 0
            .n = 1
            .Direct = FillDirect.LEFT
        End With

        Fill(fs, n)
        For i As Integer = 0 To n - 1
            For j As Integer = 0 To n - 1
                Console.Write(a(i, j) & " ")
            Next
            Console.Write(vbLf)
        Next

    End Sub



vb.net的来一个 --------------------编程问答-------------------- 上C代码,这个找到规律之后就是一个递归:

#include <stdio.h>

void ptr(int n,int c,int s,int a[100][100]) {
    int i;
    if(n>2) {
        for(i=0; i<n; i++)
            a[c+i][c]        = s, s++;
        for(i=1; i<n; i++)
            a[c+n-1][c+i]    = s, s++;
        for(i=2; i<=n; i++)
            a[c+n-i][c+n-1]  = s, s++;
        for(i=2; i<n; i++)
            a[c][n-i+c]      = s, s++;
        n -= 2, c++;
        ptr(n,c,s,a); }
    else if(n == 2) {
        a[c][c]       = s;
        a[c+1][c]     = s+1;
        a[c+1][c+1]   = s+2;
        a[c][c+1]     = s+3; }
    else if(n == 1) {
        a[c][c] = s; } }

int main() {
    int n, a[100][100], i, j;
    scanf_s("%d",&n,1);
    ptr(n,0,1,a);
    for(i=0; i<n; i++) {
        for(j=0; j<n; j++)
            printf("%4d",a[i][j]);
        printf("\n"); }
    return 0; }

个人的代码风格还望各位大大熟悉一下。 --------------------编程问答--------------------
引用 37 楼 lhblxm 的回复:
VB.NET code

    Dim a(,) As Integer
    Enum FillDirect
        RIGHT = 1
        LEFT = 2
        UP = 3
        DOWN = 4
    End Enum
    Structure arrayFillState
        Dim n As Integer
       ……



原理是
1、建立一nXn的二维数组,初始值为0
2、按顺时方向 为0则填数,不为0则拐弯
--------------------编程问答--------------------

#include <stdio.h>

int main()
{
int const n = 7;
int i, j;
int k;
int v;
int mat[n][n];
int exit = n * n;
for(i = 0; i < n; ++i) {
for(j = 0; j < n; ++j) {
mat[i][j] = 0;
}
}
for(k = 0, v = 0; ; ++k) { 
for(i = k, j = k; j < n - k; ++j) {
mat[i][j] = ++v;
if(v == exit) break;
}
if(v == exit) break;
for(i = k + 1, j = n - 1 - k; i < n - k; ++i) {
mat[i][j] = ++v;
if(v == exit) break;;
}
if(v == exit) break;
for(i = n - 1 - k, j = n - 2 - k; j > k - 1; --j) {
mat[i][j] = ++v;
if(v == exit) break;
}
if(v == exit) break;
for(i = n - 2 - k, j = k; i > k; --i) {
mat[i][j] = ++v;
if(v == exit) break;
}
if(v == exit) break;
}
for(i = 0; i < n; ++i) {
for(j = 0; j < n; ++j) {
printf("%3d", mat[i][j]);
}
printf("\n");
}
return 0;
}
--------------------编程问答-------------------- --------------------编程问答-------------------- --------------------编程问答--------------------


print "hello"
--------------------编程问答-------------------- LZ,你看我的程序可以么?别忘了给分呀!

using System;

namespace CsdnTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入n:");
            int n = int.Parse(Console.ReadLine());

            if (n == 1)
            {
                Console.WriteLine("1");
            }
            else if (n == 2)
            {
                Console.WriteLine("1 2");
                Console.WriteLine("4 3");
            }
            else if (n == 3)
            {
                Console.WriteLine("1 2 3");
                Console.WriteLine("8 9 4");
                Console.WriteLine("7 6 5");
            }
            else if (n == 4)
            {
                Console.WriteLine("1 2 3 4");
                Console.WriteLine("12 13 14 5");
                Console.WriteLine("11 16 15 6");
                Console.WriteLine("10 9 8 7");
            }
            else
                Console.WriteLine("不要和我开玩笑,你输入的数字太大了,这很不友好!");
        }
    }
}
--------------------编程问答-------------------- #include <iostream>
#include <vector>
using namespace std;

class Test
{
public:
Test(int num) : number(num),tnum(1),row(0),col(-1),left(-1),right(num),up(-1),down(num)
{
V.resize(num * num,0);
}

void Right()
{
while (++col < right)
{
V[row * number + col] = tnum;
++tnum;
}
--col;
++up;
}
void Down()
{
while(++row < down)
{
V[row * number + col] = tnum;
++tnum;
}
--row;
--right;
}
void Left()
{
while(--col > left)
{
V[row * number + col] = tnum;
++tnum;
}
++col;
--down;
}
void Up()
{
while(--row > up)
{
V[row * number + col] = tnum;
++tnum;
}
++row;
++left;
}

void Run()
{
while (tnum <= number * number)
{
if(tnum <= number * number)  // 向右
Right();
if(tnum <= number * number)  // 向下
Down();
if(tnum <= number * number)  // 向左
Left();
if(tnum <= number * number)  // 向上
Up();
}
}
void Print() const
{
for(vector<int>::size_type i = 1; i <= V.size(); ++i)
{
cout << V[i-1] << "\t";
if (i % number == 0)
cout << endl;
}
}

private:
int number;              // 输入的数
int left,right,up,down;  // 上下左右边界
int             col,row;             // 数的行和列
int tnum;                // 要打印的数
vector<int>     V;                   // 按打印顺序把数存储起来
};

int main()
{
int num;

cout << "Input the number : ";
cin >> num;

Test t(num);
t.Run();
t.Print();

system("pause");
return 0;
} --------------------编程问答-------------------- #include <iostream>
#include <vector>
using namespace std;

class Test
{
public:
      Test(int num) : number(num),tnum(1),row(0),col(-1),left(-1),right(num),up(-1),down(num)
      {
            V.resize(num * num,0);
      }

      void Right()
      {
            while (++col < right)
            {
                  V[row * number + col] = tnum;
                  ++tnum;
            }
            --col;
            ++up;
      }

      void Down()
      {
            while(++row < down)
            {
                V[row * number + col] = tnum;
++tnum;
            }
            --row;
            --right;
      }
      
      void Left()
      {
           while(--col > left)
           {
                V[row * number + col] = tnum;
                ++tnum;
           }
           ++col;
           --down;
      }

      void Up()
      {
          while(--row > up)
          {
                V[row * number + col] = tnum;
                ++tnum;
          }
          ++row;
          ++left;
      }

      void Run()
      {
           while (tnum <= number * number)
           {
                if(tnum <= number * number)   // 向右
                     Right();
                if(tnum <= number * number)   // 向下
                     Down();
                if(tnum <= number * number)   // 向左
                     Left();
                if(tnum <= number * number)   // 向上
                     Up();
           }
      }

      void Print() const
      {
            for(vector<int>::size_type i = 1; i <= V.size(); ++i)
            {
                  cout << V[i-1] << "\t";
                  if (i % number == 0)
                     cout << endl;
            }
      }

private:
        int          number;                 // 输入的数
        int          left,right,up,down;     // 上下左右边界
        int          col,row;                // 数的行和列
        int          tnum;                   // 要打印的数
        vector<int>  V;                      // 按打印顺序把数存储起来
};

int main()
{
        int num;

        cout << "Input the number : ";
        cin >> num;

        Test t(num);
        t.Run();
        t.Print();

        system("pause");
        return 0;
}

发帖混分~~~给点分呗~~~ --------------------编程问答-------------------- 就是给定一个数,求以这个数为维数的一个矩阵,矩阵的元素是按一个由外到内循环的自然数的排列. --------------------编程问答-------------------- 别扯淡了,自己查吴文虎的中学信息学竞赛教材。就你这水平别
TMD装B。 --------------------编程问答-------------------- 仔细分析下应该不难吧 --------------------编程问答--------------------
引用 44 楼 litaoye 的回复:
LZ,你看我的程序可以么?别忘了给分呀!

C# code
using System;

namespace CsdnTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入n:");
            int ……

您太强了! 怪不得能挂这么多牌…… --------------------编程问答-------------------- --------------------编程问答-------------------- 不理解5上和6下为啥会有空的 --------------------编程问答-------------------- 昨天太晚了 没时间贴上来 发现C#需要好多行啊 我用C写了一个比较简陋的 才61行 请指教

#include <stdio.h>
#include <stdlib.h>

int s[1024] = {0};

int main(int argc,char ** argv )
{
int n;
if(argv[1]==NULL) n = 6; 
else n = atoi(argv[1]);

int dir = 1;

int i,j,k;

for(i=1;i<=n;i++)
{
s[i] = i;
}

int x = n;
int y = 1;
int t = n+1;
for(i=(n-1);i>0;i--)
{
for(j=1;j<=2;j++)
{
for(k=1;k<=i;k++)
{
switch (dir%4)
{
case 0:
x++;
break;
case 1:
y++;
break;
case 2:
x--;
break;
case 3:
y--;
break;
default:
break;
}
printf("[%d,%d]:%d DIR:%d\n", x, y, t, dir%4);
s[(y-1)*n+x] = t;
t++;
}
dir ++;
}
}

for(i=1;i<=n*n;i++)
{
printf("-%02d-", s[i]);
if(i%n==0) printf("\n");
}
}


--------------------编程问答--------------------
引用 53 楼 wshn13 的回复:
昨天太晚了 没时间贴上来 发现C#需要好多行啊 我用C写了一个比较简陋的 才61行 请指教
C/C++ code

#include <stdio.h>
#include <stdlib.h>

int s[1024] = {0};

int main(int argc,char ** argv )
{
    int n;
    if(argv[1]==NULL) n = 6; 
   ……


写的比较匆忙 没有注释  --------------------编程问答-------------------- 给的例子明明是逆时针递减 --------------------编程问答--------------------
引用 44 楼 litaoye 的回复:
LZ,你看我的程序可以么?别忘了给分呀!


C# code
using System;

namespace CsdnTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入n:");
      ……


哈哈哈,这个最经典!!! --------------------编程问答--------------------
引用 44 楼 litaoye 的回复:
LZ,你看我的程序可以么?别忘了给分呀!

C# code
using System;

namespace CsdnTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入n:");
            int ……
这位哥哥,强大的很纳~哈哈 --------------------编程问答-------------------- 晕 发现用C比较容易 --------------------编程问答--------------------
引用 53 楼 wshn13 的回复:
昨天太晚了 没时间贴上来 发现C#需要好多行啊 我用C写了一个比较简陋的 才61行 请指教
C/C++ code

#include <stdio.h>
#include <stdlib.h>

int s[1024] = {0};

int main(int argc,char ** argv )
{
    int n;
    if(argv[1]==NULL) n =……
强帖留名 --------------------编程问答--------------------  private static void fun()
        {
            int N = Convert.ToInt32(System.Console.ReadLine());//总数
            int Q;                                              //行数
            double q = System.Math.Sqrt(N);                     //近似行数
            int R;                                              //行数
            int C;                                              //列数

            //----------------获取行数和列数--------------------------
            Q = (int)q;
            if (Q < q)                                          //不能完全开平方
            {
                Q = Q + 1;
                R = Q;
                C = Q - 1;
            }
            else
            {
                R = Q;
                C = Q;
            }
            int MAX = Q * C;
            if (MAX < N)
                C = C + 1;
            MAX = Q * C;
            //----------------------------------------------------------
            int[,] data = new int[R, C];//定义数据数组

            //初始化数组
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                    data[i, j] = -1;
            }
            int row = 0;
            int cell = 0;
            int rowAdd = 0;
            int cellAdd = 1;
            for (int i = 0; i < MAX - N; i++)
            {
                data[0, i] = 0;
            }
            cell = MAX - N;
            //数组赋值
            for (int i = 1; i <= N; i++)
            {
                data[row, cell] = i;
                int tempRow = row + rowAdd;
                int tempCell = cell + cellAdd;

                if (tempRow < 0 || tempRow >= R || tempCell < 0 || tempCell >= C || data[tempRow, tempCell] != -1)//切换行或列的步长
                {
                    if (rowAdd == 0 && cellAdd == 1)
                    {
                        rowAdd = 1;
                        cellAdd = 0;
                    }
                    else if (rowAdd == 0 && cellAdd == -1)
                    {
                        rowAdd = -1;
                        cellAdd = 0;
                    }
                    else if (rowAdd == 1 && cellAdd == 0)
                    {
                        cellAdd = -1;
                        rowAdd = 0;
                    }
                    else if (rowAdd == -1 && cellAdd == 0)
                    {
                        rowAdd = 0;
                        cellAdd = 1;
                    }

                }
                //下一个要赋值的行和列
                row = row + rowAdd;
                cell = cell + cellAdd;

            }
            for (int i = 0; i < Q; i++)
            {
                for (int k = 0; k < C; k++)
                {
                    if (data[i, k] == 0)
                        System.Console.Write("  ");
                    else
                        System.Console.Write(data[i, k].ToString());

                    System.Console.Write("\t");
                }
                System.Console.WriteLine();
            }
        }
在main中调用及ok了

--------------------编程问答-------------------- 晕看错题目,按楼主说的其实蛮简单的,算法和上面一样:
  private static void F()
        {
            int N = Convert.ToInt32(System.Console.ReadLine());//总数          
            int R;                                              //行数
            int C;                                              //列数
            R = N;
            C = N;           
            int[,] data = new int[R, C];//定义数据数组

            //初始化数组
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                    data[i, j] = 0;
            }
            int row = 0;
            int cell = 0;
            int rowAdd = 0;
            int cellAdd = 1;            
            //数组赋值
            for (int i = 1; i <= N*N ; i++)
            {
                data[row, cell] = i;
                int tempRow = row + rowAdd;
                int tempCell = cell + cellAdd;

                if (tempRow < 0 || tempRow >= R || tempCell < 0 || tempCell >= C || data[tempRow, tempCell] != 0)//切换行或列的步长
                {
                    if (rowAdd == 0 && cellAdd == 1)
                    {
                        rowAdd = 1;
                        cellAdd = 0;
                    }
                    else if (rowAdd == 0 && cellAdd == -1)
                    {
                        rowAdd = -1;
                        cellAdd = 0;
                    }
                    else if (rowAdd == 1 && cellAdd == 0)
                    {
                        cellAdd = -1;
                        rowAdd = 0;
                    }
                    else if (rowAdd == -1 && cellAdd == 0)
                    {
                        rowAdd = 0;
                        cellAdd = 1;
                    }
                }
                //下一个要赋值的行和列
                row = row + rowAdd;
                cell = cell + cellAdd;

            }
            for (int i = 0; i < R ; i++)
            {
                for (int k = 0; k < C; k++)
                {
                    if (data[i, k] == 0)
                        System.Console.Write("  ");
                    else
                        System.Console.Write(data[i, k].ToString());

                    System.Console.Write("\t");
                }
                System.Console.WriteLine();
            }
        }

--------------------编程问答-------------------- 用递归来解,代码比较少呢
static void Main(string[] args)
        {
            int iInput;
            iInput =int.Parse ( Console.ReadLine());

            int[,] ret = new int[iInput, iInput];

            GetStruct(ref ret, 0, 0, 1, iInput);


            for (int i = 0; i < iInput; i++)
            {
                for (int j = 0; j < iInput; j++)
                {
                    Console.Write(ret[i, j].ToString () + " ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();


        }

        static void GetStruct(ref int[,] ret, int x, int y,int Start,int Level)
        {
            int iNumber;
            iNumber = Start;
            if (Level == 1 )

            {
                ret[x, y] = iNumber;
            }
            else
                {
                for (int i = 0; i < Level - 1; i++)
                {
                    ret[x, y+i] = iNumber;
                    iNumber++;
                }
                for (int i = 0; i < Level - 1; i++)
                {
                    ret[x + i, y+Level - 1] = iNumber;
                    iNumber++;
                }

                for (int i = 0; i < Level - 1; i++)
                {
                    ret[x + Level - 1, y+Level - 1-i] = iNumber;
                    iNumber++;
                }

                for (int i = 0; i < Level - 1; i++)
                {
                    ret[x + Level - 1-i, y] = iNumber;
                    iNumber++;
                }

                if (Level - 2 >= 0)
                {
                    GetStruct(ref ret, x + 1, y + 1, iNumber, Level - 2);
                }
            }
            

        } --------------------编程问答-------------------- 这个问题去谷歌找回很精确的  现在要午休了 要不就给你COPY一份了 加油 --------------------编程问答--------------------
	int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

int n;
printf("n="); //max 256
scanf("%d", &n);
int m[256][256] = {0};
memset(m, 0, 256*256*sizeof(int));
int x = 0;
int y = 0;
int direction = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
int t = (i) * n + j + 1;
m[x][y] = t;
int nx = x + dx[direction];
int ny = y + dy[direction];
//new position is invalid, or already set
//turn right.
if (nx < 0 || nx >= n || ny < 0 || ny >= n || m[nx][ny] != 0) {
direction  = (direction + 1) % 4;
nx = x + dx[direction];
ny = y + dy[direction];
}
x = nx; y = ny;

}

}

/// output

for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
printf("%d ", m[j][i]);
}
printf("\n");
}
--------------------编程问答-------------------- 四年前做过的路人飘过!
还有一句,小子!这里是技术社区,不是作秀场! --------------------编程问答--------------------

static void Main(string[] args)
{
    Console.Write("Please input n:");
    int n = Convert.ToInt32(Console.ReadLine());

    int[,] arr=new int[n,n];
    int x = 0;
    int y = 0;
    string direction = "right";

    for (int i = 1; i <= n * n;i++ )
    {
        switch (direction) { 
            case "right":
                arr[x, y++] = i;
                if (y == n || arr[x, y] != 0)//如果当前列索引为n(到了最右), 或当前元素右边的元素不为0, 转下
                {   
                    direction = "bottom";
                    y--;
                    x++;
                }
                break;
            case "bottom":
                arr[x++, y] = i;
                if (x == n || arr[x, y] != 0)//如果当前行索引为n(到了最下), 或当前元素下边的元素不为0, 转左
                {
                    direction = "left";
                    x--;
                    y--;
                }
                break;
            case "left":
                arr[x, y--] = i;
                if (y == -1 || arr[x, y] != 0)//如果当前列索引为-1(到了最左), 或当前元素左边的元素不为0, 转上
                {
                    direction = "top";
                    y++;
                    x--;
                }
                break;
            case "top":
                arr[x--, y] = i;
                if (arr[x, y] != 0)//如果上面的一行不为0, 转右
                {
                    direction = "right";
                    x++;
                    y++;
                }
                break;
        }
    }

    for (int i = 0; i < arr.GetLength(0); i++) {
        for (int j = 0; j < arr.GetLength(1); j++) {
            Console.Write(arr[i,j]+"\t");
        }
        Console.WriteLine();
    }
    Console.ReadLine();
}
--------------------编程问答-------------------- 都厉害 ,俺代码都整不明白~ --------------------编程问答-------------------- 这个题目大学老师不会?
坑爹呢~ --------------------编程问答-------------------- 用java实现的


/**
 * @author troy(J2EE)
 * @version 1.0
 */
public class Test{
private static int v=1;//起始值
private static int x=2;//起始 x坐标
private static int y=2;//起始 y坐标
private static int m=12;//数组的大小
public static void  main(String[] args){
int[][] s=new int[m][m]; 
luoxuan(s,8);
for(int i=0 ; i <s.length ; i++) { 
            for(int j=0 ; j<s[i].length;j++) { 
                System.out.print(s[i][j]+"\t") ; 
            }
System.out.println();
        }

}
/*/
 * 顺时针螺旋递减等差数列矩阵
 */
public static void luoxuan(int[][] s,int value){
if(s[x][y]!=0){
return;
}
//→
for(int i=1;i<=value;i++,v++){
s[x][y+i-1]=v;
}
//↓
for(int i=1;i<value;i++){
s[x+i][y+value - 1]=s[x][y+value-1]+i;
}
//←
for(int i=1;i<value;i++){
s[x+value-1][y+value-i-1]=s[x+value-1][y+value-1]+i;
}
//↑
for(int i=1;i<value - 1;i++){
s[x+value-i-1][y+0]=s[x+value-1][y+0]+i;
v=s[x+value-1][y+0]+i+1;
}
x++;
y++;
value=value-2;
luoxuan(s,value);
}
}



---------- java1.5 -- 运行 ----------
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 2 3 4 5 6 7 8 0 0
0 0 28 29 30 31 32 33 34 9 0 0
0 0 27 48 49 50 51 52 35 10 0 0
0 0 26 47 60 61 62 53 36 11 0 0
0 0 25 46 59 64 63 54 37 12 0 0
0 0 24 45 58 57 56 55 38 13 0 0
0 0 23 44 43 42 41 40 39 14 0 0
0 0 22 21 20 19 18 17 16 15 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0

输出完毕 (耗时 0 秒) - 正常终止 --------------------编程问答-------------------- 可以修改参数:

private static int v=1;//起始值
private static int x=0;//起始 x坐标
private static int y=0;//起始 y坐标
private static int m=8;//数组的大小

---------- java1.5 -- 运行 ----------
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15

输出完毕 (耗时 0 秒) - 正常终止 --------------------编程问答-------------------- private static int v=1000;//起始值
private static int x=0;//起始 x坐标
private static int y=0;//起始 y坐标
private static int m=8;//数组的大小


---------- java1.5 -- 运行 ----------
1000 1001 1002 1003 1004 1005 1006 1007
1027 1028 1029 1030 1031 1032 1033 1008
1026 1047 1048 1049 1050 1051 1034 1009
1025 1046 1059 1060 1061 1052 1035 1010
1024 1045 1058 1063 1062 1053 1036 1011
1023 1044 1057 1056 1055 1054 1037 1012
1022 1043 1042 1041 1040 1039 1038 1013
1021 1020 1019 1018 1017 1016 1015 1014

输出完毕 (耗时 0 秒) - 正常终止 --------------------编程问答-------------------- --------------------编程问答-------------------- --------------------编程问答-------------------- 个人认为18楼的简洁。 --------------------编程问答-------------------- 学习了,整天灌水还能大胃王!赚了 --------------------编程问答-------------------- iisahandsomeboy
 
(iisahandsomeboy) 

等 级: 0级
结帖率:50.00% 

楼主走了,不给结贴了 --------------------编程问答-------------------- 凑下热闹。。不考虑效率,只考虑结果。

using System;

namespace ConsoleApplication3
{
    class Program
    {
        static int _count = 1;
        private static int N = 0;
        static void Main(string[] args)
        {
            // ----输入一个大于0的数字
            int n = int.Parse(Console.ReadLine());
            while (n>0)
            {
                _count =1;
                //--
                N = n;
                int[,] data = new int[n, n];
                // -------填充数组
                HaveATry(data, n, 0);

                // -------打印显示数组
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        Console.Write(data[i, j].ToString() + "    ");
                    }
                    Console.WriteLine("   ");
                }
                n = int.Parse(Console.ReadLine());
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="n"></param>
        /// <param name="cen">填充第几层</param>
        public static void HaveATry(int[,] data, int n, int cen)
        {
            if ( N / 2.0 < cen)
            {
                return;

            }
            // --例如从[0,0]到[0,n-1]
            for (int i = cen; i < n; i++)
            {
                data[cen, i] = _count++;

            }
            _count--;//a[0][n-1]要赋值2次所以要自减一下

            // --例如从[0,n-1]到[n-1,n-1]
            for (int i = cen; i < n; i++)
            {
                data[i, n - 1] = _count++;
            }
            _count--;
            // --例如从例如从[n-1,n-1]到[n-1,0]
            for (int i = n - 1; i >= cen; i--)
            {
                data[n - 1, i] = _count++;
            }
            _count--;
            // --例如从例如从[n-1,0]到[0,1]
            for (int i = n - 1; i > cen; i--)
            {
                data[i, cen] = _count++;
            }
            HaveATry(data, n - 1, ++cen);
        }
    }
}

--------------------编程问答-------------------- using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TwoArray
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strShow  = ShowTwoArray(Convert.ToInt16(textBox1.Text.ToString()));

            textBox2.Text = strShow;

        }

        private string ShowTwoArray(int arrNum)
        {
            int [,] ret = new int[arrNum,arrNum];               //结果数组
            bool blChangDir = false;                            //是否变化旋转方向
            int intdir = 1;                                     //旋转方向
            int x = 0;
            int y = 0;                                      
            int intBignumX = arrNum;
            int intBigNumY = 0;
            string strShow = "";

            for (int i = 1; i < (arrNum * arrNum) + 1; i++)
            {
                if (blChangDir)
                {
                    if (intdir < 4)
                    {
                        intdir++;
                    }
                    else
                    {
                        intdir = 1;
                        intBignumX--;
                        intBigNumY++;
                    }

                    blChangDir = false;                            
                }

                ret[x, y] = i;

                switch (intdir)
                {
                    case 1:

                        if (y < intBignumX - 1)
                        {
                            y++;
                        }
                        else
                        {
                            x++;
                            blChangDir = true;
                        }
                        break;
                    case 2:
                        if (x < intBignumX - 1)
                        {
                            x++;
                        }
                        else
                        {
                            y--;
                            blChangDir = true;
                        }
                        break;
                    case 3:
                        if (y > intBigNumY)
                        {
                            y--;
                        }
                        else
                        {
                            x--;
                            blChangDir = true;
                        }
                        break;
                    case 4:
                        if (x > intBigNumY+1)
                        {
                            x--;
                        }
                        else
                        {
                            y++;
                            blChangDir = true;
                        }
                        break;

                }
            }

            for (int i = 0; i < arrNum; i++)
            {
                for (int j = 0; j < arrNum; j++)
                {
                    strShow = strShow + ret[i, j].ToString() + " ";
                }

                strShow = strShow + "\r\n";
                
            }

            return strShow;
        }
    }
}


来凑个热闹,借用楼上的思路,代码简陋,见笑了 --------------------编程问答-------------------- #include<stdio.h>
#include<stdlib.h>

//下标定位
#define INDEX(i,j) ((i)*(N)+(j))

int main()
{
  int t=0;
  int p=1;
  int h=0;
  int n=0;
  int *a;
  int i=0,j=0;

  int N;
  scanf("%d",&N);
  n=N;
  a=malloc(N*N*sizeof(int));

  while(4*n-4>0)
   {
     while(p<=h+n)
      //a[i*N+(j++)]=p++;
      a[INDEX(i,j++)]=p++;

      j--;
      i++;
     while(p<=h+n+n-1)
      //a[(i++)*N+j]=p++;
      a[INDEX(i++,j)]=p++;
       
     i--;
     j--;
     while(p<=h+n+n-1+n-1)
      //a[i*N+(j--)]=p++;
      a[INDEX(i,j--)]=p++;

     i--;
     j++;
     while(p<=h+n+n-1+n-1+n-2)
      //a[(i--)*N+j]=p++;
      a[INDEX(i--,j)]=p++;
      
     i++;
     j++;
      
     t++;
     n=N-2*t;
     h=p-1;
   }
   
   if(N%2!=0)
      //a[i*N+j]=N*N;
      a[INDEX(i,j)]=N*N;

  for(i=0;i<N;i++)
   {
    for(j=0;j<N;j++)
       { 
          //printf("%3d ",a[i*N+j]);
          printf("%3d ",a[INDEX(i,j)]);
       }
    printf("\n");
   }
  
   free(a);
  return 0;
} --------------------编程问答-------------------- 我写的一个  程序很简单  死了我不少脑细胞 --------------------编程问答-------------------- 标题党    --------------------编程问答-------------------- 有意思,自己也弄个来做做。多锻炼下 --------------------编程问答-------------------- 我曾经做过这题,看看我的文章吧

http://www.blogjava.net/china-qd/archive/2007/06/25/126154.html --------------------编程问答-------------------- --------------------编程问答-------------------- 自己的代码,做一下说明以及详细的注释,上面那些写的确实看得不大懂,这些递归代码没注释自己看着都有一些迷糊,我个人的想法是:从外向内,一圈圈的将结果保存到一个二维数组中,然后打印这个数组就行了。今天重新看了下楼主的题,自己以前放出的代码这个方向不对,见38楼,这次改正后的代码能达到楼主的要求。打印的貌似数字不能太大,不然格式会乱掉。办法有点笨,但是理解起来比较容易吧,个人觉得。
#include <stdio.h>

void ptr(int n,int c,int s,int a[100][100]) {//n是你打印的维数,c是起始的数组位置:a[c][c],s是
    int i;                                                     //这个位置要打印的数字,a那个自然是打印输出数字的数组了
    if(n>2) {//如果n>2的话,就是说里面还有大于1圈需要打印,打印最外的一圈,然后递归打印其余内层圈
        for(i=0; i<n; i++)                           //先是打印第一行
            a[c][c+i]             = s, s++;         
        for(i=1; i<n; i++)                           //转弯,打印最后一列
            a[c+i][c+n-1]     = s, s++;
        for(i=2; i<=n; i++)                        //继续转弯,逆向打印最后一行
            a[c+n-1][n-i+c]  = s, s++;
        for(i=2; i<n; i++)                          //继续转弯,逆向打印第一列
            a[c+n-i][c]          = s, s++;
        n -= 2, c++;                 //因为打印了一圈,所以维数减2,起始地址向右下移动一格(a[c+1][c+1])
        ptr(n,c,s,a); }                //递归打印内层圈
    else if(n == 2) {               //如果等于2或者等于1,也就是说里层只有一圈,节省时间,直接打印
        a[c][c]            = s;
        a[c][c+1]        = s+1;
        a[c+1][c+1]   = s+2;
        a[c+1][c]        = s+3; }
    else if(n == 1) {                //这个判断可以去掉的说,因为不存在第三种情况……
        a[c][c] = s; } }

int main() {
    int n, a[100][100], i, j;
    scanf_s("%d",&n,1);
    ptr(n,0,1,a);                                                //递归调用的打印函数
    for(i=0; i<n; i++) {
        for(j=0; j<n; j++)
            printf("%4d",a[i][j]);                           //最后打印这个所有数字都已经按照顺序排列的二维数组
        printf("\n"); }
    return 0; }

好了,这道题C就是这么写,这个题是以前csdn曾经发过的一道网易游戏面试题,具体在哪里记不大清楚了,和这个一样,只是顺序换了下。
http://qzone.qq.com/chn.skill
Leap yourself, Leap ahead. --------------------编程问答--------------------
#include<iomanip>
#include<iostream>
using namespace std ;
int main()
{
int n ;
while( cin>>n )
{
int i = 0 , j = 0 , k = 1 ;
int marix[100][100] = { 1 } ;
while( k < n*n  )
{
while( j < n - 1 && marix[i][j+1] == 0 )
marix[i][++j] = ++k ;
while( i < n - 1 && marix[i+1][j] == 0 )
marix[++i][j] = ++k ;
while( j > 0 && marix[i][j-1] == 0 )
marix[i][--j] = ++k ;
while( i > 0 && marix[i-1][j] == 0 )
marix[--i][j] = ++k ;
}
for( i = 0 ; i < n ; i++ )
{
for( j = 0 ; j < n ; j++ )
cout<<setw(4)<<marix[i][j]<<' ' ;
cout<<endl ;
}
}
return 0 ;
}


大一学生留个名
--------------------编程问答-------------------- 额,csdn上怎么插入源代码的那个功能怎么用? --------------------编程问答-------------------- 恕在下无能,这明明是个顺时针螺旋递增等差数列矩阵呀,请求大虾解释? --------------------编程问答-------------------- 难不成这个递减是从上到下的与螺旋递减,我只能理解到这份上拉,明天我得从幼儿园上起拉 --------------------编程问答-------------------- 此有何难?
答曰:寻路问题。 --------------------编程问答-------------------- 来个牛的!

static void Main(string[] args)
{
    int r = 0, c = -1, s = 4, i = 0, j, loop = s;    // s是大小
    int[,] a = new int[s, s];
    while (i < s * s)
    {
        for (j = 0; j < loop; ++j) a[r, ++c] = ++i; --loop;
        for (j = 0; j < loop; ++j) a[++r, c] = ++i;
        for (j = 0; j < loop; ++j) a[r, --c] = ++i; --loop;
        for (j = 0; j < loop; ++j) a[--r, c] = ++i;
    }
    for (i = 0; i < s * s; ++i)
    {
        if (i % s == 0) Console.WriteLine();
        Console.Write("{0,4}", a[i / s, i % s]);
    }
    Console.ReadKey();
}
--------------------编程问答-------------------- 各种思路各种解法 马克一下 --------------------编程问答-------------------- 我用java的也来凑下热闹。
不过我这个版本不是正方形的,是矩形。
而且我感觉这个方法比较好理解,intuitive。

import java.util.Scanner;
public class Test {
public static int turns;//转弯的次数。
public static int x = 1;//column的坐标。
public static int y = 1;//row的坐标。

public static void main(String[] args)  {
Scanner scanner = new Scanner(System.in);
System.out.println("Please give a row number:");
int row = scanner.nextInt();
System.out.println("Please give a column number:");
int column = scanner.nextInt();
int[][] matrix = new int[row + 2][column + 2];//建一个边缘缓冲的矩阵,比实际需要的大了一圈。
//这样可以防止超出边界;
for (int i = 1; i < row + 1; i++) {
for (int j = 1; j < column + 1; j++) {
matrix[i][j] = -1;//实际需要的内部矩阵初始化为-1。
}
}
for (int i = 0; i < row * column; i++) {

if (matrix[y][x] == -1) {
matrix[y][x] = i + 1;
} else {
lastPoint();//如果不等于-1,说明在边界上,或已经赋过值了,后退一格。
turns++;//转向。
i--;//因为这轮matrix没变化,白走一轮。
}
nextPoint();

}
display(matrix);
}

public static void nextPoint() {
switch (turns % 4) {//每四次转弯回到同一方向。
case 0:
x++;
break;
case 1:
y++;
break;
case 2:
x--;
break;
case 3:
y--;
}
}

public static void lastPoint() {
switch (turns % 4) {//和nextPoint正好相反。
case 0:
x--;
break;
case 1:
y--;
break;
case 2:
x++;
break;
case 3:
y++;
}
}

public static void display(int[][] matrix) {
for (int i = 1; i < matrix.length -1; i++) {
for (int j = 1; j < matrix[0].length - 1; j++) {
System.out.printf("%2d ", matrix[i][j]);
}
System.out.println();
}
}
}
--------------------编程问答-------------------- 先从正对角线上入手,在从反对角线处理,算法会大大简化。 --------------------编程问答-------------------- 来个直观的.

void Fill(int n) {
int d = 0;
int Directions[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};  // 右, 下, 左, 上
int Matrix[100][100] = {0};
int x = 0, y = -1;
int xx = 0, yy = -1;
int cnt = n * n;
if (n > 100) {
cout << "are you kidding?" << endl;
return;
}
for(int i = 1; i <= cnt; i++) {
xx = x + Directions[d][0];
yy = y + Directions[d][1];
if (xx >= n || xx < 0 || yy >= n || yy < 0 || Matrix[xx][yy] != 0) {
                        // 转弯
d = (d + 1) % 4;
}
x += Directions[d][0];
y += Directions[d][1];
Matrix[x][y] = i;
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cout << Matrix[i][j] << "\t";
}
cout << endl;
}
}

--------------------编程问答-------------------- 我是先归纳了数学规律后然后再做的,没用数组,因为有规律的,所以数组派不上用场

#include <stdio.h>
int main()
{
    int n=0,i;
    while(1)
    {
    printf("\nEnter a number:"); scanf("%d",&n);
    printf("The result is:\n");
    for(i=0; i<n*n; i++)
    {
            /* 左上角为原点,(i/n, i%n)为坐标 */
            int k = i/n > (n-1-i/n)? (n-1-i/n):i/n;
            k = k > i%n ? (i%n) : k;
            k = k > (n-1-i%n)? (n-1-i%n) : k;    
            /* 以一个圈为一个回环,算出点在哪个回环上 */
            if((i/n==k)&&(i%n<n-k)) printf("%d ",4*k*(n-k)+i%n+1-k);/* 上回环  */
            else if(((n-1-i%n)==k)&&(i/n>k)) printf("%d ",4*k*(n-k)+(n-2*k-1)+i/n+1-k);/* 右回环 */ 
            else if (((n-1-i/n)==k)) printf("%d ",4*k*(n-k)+3*(n-2*k-1)-i%n+1+k);/*下回环 */             
            else if((i%n==k)&&(i/n<n-k)) printf("%d ",4*(k+1)*(n-k-1)-i%n-1+k+1);/* 左回环  */            
            if((i+1)%n==0) printf("\n");
     }
    }
    return 0;
}        
--------------------编程问答-------------------- 我是96楼的,贴代码时不小心复制错了...

#include <stdio.h>
int main()
{
    int n=0,i;
    while(1)
    {
    printf("\nEnter a number:"); scanf("%d",&n);
    printf("The result is:\n");
    for(i=0; i<n*n; i++)
    {
            /* 左上角为原点,(i/n, i%n)为坐标 */
            int k = i/n > (n-1-i/n)? (n-1-i/n):i/n;
            k = k > i%n ? (i%n) : k;
            k = k > (n-1-i%n)? (n-1-i%n) : k;    
            /* 以一个圈为一个回环,算出点在哪个回环上 */
            if((i/n==k)&&(i%n<n-k)) printf("%d ",4*k*(n-k)+i%n+1-k);/* 上回环  */
            else if(((n-1-i%n)==k)&&(i/n>k)) printf("%d ",4*k*(n-k)+(n-2*k-1)+i/n+1-k);/* 右回环 */ 
            else if (((n-1-i/n)==k)) printf("%d ",4*k*(n-k)+3*(n-2*k-1)-i%n+1+k);/*下回环 */             
            else if((i%n==k)) printf("%d ",4*(k+1)*(n-k-1)-i/n+k+1);/* 左回环  */            
            if((i+1)%n==0) printf("\n");
     }
    }
    return 0;
}        
--------------------编程问答-------------------- 不明白  题目 --------------------编程问答-------------------- 好人和牛人 都同时存在 --------------------编程问答-------------------- 这么多高手 过来学习了.
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,