机试指南第二章-经典入门-排版例题自解

例2.8 叠筐

解题思路

这题的思路很有启发性,先排版后输出,及时阻止了我动规。

AC代码

#include<cstdio>
#include<iostream>

using namespace std;
int m[82][82];
char a, b;
int n;

int main()
{
    bool flag = true;
    while (scanf("%d %c %c", &n, &a, &b) != EOF)
    {
        if (flag)flag = false;
        else printf("
");
        for (int i = 1, j = 1; i <= n; i += 2, j++)//从里到外输出每个圈,i是各圈边长,j是圈数
        {
            int x = n / 2 + 1, y = x;//中心点
            x -= j - 1;
            y -= j - 1;//各圈左上角点坐标
            char c = j % 2 == 1 ? a : b;//各圈字符
            for (int k = 1; k <= i; k++)//对当前圈赋值
            {
                m[x + k - 1][y] = c;
                m[x][y + k - 1] = c;
                m[x + i - 1][y + k - 1] = c;
                m[x + k - 1][y + i - 1] = c;
            }
        }
        if (n != 1)
        {
            m[1][1] = ' ';
            m[n][1] = ' ';
            m[1][n] = ' ';
            m[n][n] = ' ';
        }
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                printf("%c", m[i][j]);
            }
            printf("
");
        }
    }
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/yun-an/p/11128849.html