zoukankan      html  css  js  c++  java
  • 回形矩阵

    回型矩阵:

    输入一个数字n,输出n阶回型矩阵

    例如:输入5

    输出

    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 7 。。。。

    紧接着是下面和左边

    依次进行,一圈一圈知道完成结果。

    #include<stdio.h>
    
    void Visit(int a[][100],int n)
    {
        int p=0,q=n-1;
        int count=0;
    
        while(count<n*n)
        {
            for(int i=p;i<=q;i++)//从上面开始赋值
                a[p][i]=++count;
    
            for(int i=p+1;i<=q;i++)//从右边开始赋值
                a[i][q]=++count;
    
            for(int i=q-1;i>=p;i--)//从下面开始赋值
                a[q][i]=++count;
    
            for(int i=q-1;i>=p+1;i--)
                a[i][p]=++count;
                p++;
                q--;
        }
    
    
    }
    
    void Print(int a[][100],int n)
    {
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
                printf("%2d ",a[i][j]);
            printf("
    ");
        }
    }
    
    int main()
    {
        int n,a[100][100];
        scanf("%d",&n);
        Visit(a,n);
        Print(a,n);
        return 0;
    }
    



  • 相关阅读:
    Python 从入门到实践
    Python 斐波那契数列
    Python 纸牌游戏
    Python hangman小游戏
    BC #49 1001 Untitled
    BC#50 1003 The mook jong
    BC #50 1001 Distribution money
    vector
    stack
    queue
  • 原文地址:https://www.cnblogs.com/gaot/p/7709695.html
Copyright © 2011-2022 走看看