画矩形

GitHub跳转原题关系图返回列表

按行判断边界或实心状态,拼接并输出指定字符的矩形。

OJ: noi_openjudge

题目 ID: ch0105-42

难度:入门

标签:模拟字符串python

日期: 2026-07-30 23:01

题意

按给定高、宽和字符输出矩形。参数为 1 时输出实心矩形,为 0 时仅保留边界字符,内部用空格填充。

思路

逐行输出。首行和末行一定全由绘制字符组成;中间行在实心模式下也全填字符,在空心模式下拼出“左边界 + 中间空格 + 右边界”。

题目保证宽至少为 55,所以中间空格数 width - 2 始终合法。

代码

Python代码

python
height_text, width_text, character, filled_text = input().split()
height = int(height_text)
width = int(width_text)
filled = filled_text == "1"

for row in range(height):
    is_border = row == 0 or row == height - 1
    if filled or is_border:
        print(character * width)
    else:
        print(character + " " * (width - 2) + character)

C++代码

cpp
#include <cstdio>


int main(){
    int h,w,flag;
    char c;
    scanf("%d%d",&h,&w);
    scanf("%c",&c);
    scanf("%c",&c);
    scanf("%d",&flag);
    int i,j,k;

    // line 1
    for (i=1;i<=w;i++){
        printf("%c",c);
    }
    printf("\n");


    for (i=1;i<=h-2;i++){
        printf("%c",c);
        for (j=1;j<=w-2;j++){
            if(flag)
                printf("%c",c);
            else 
                printf(" ");
        }
        printf("%c\n",c);
    }




    // line last
    for (i=1;i<=w;i++){
        printf("%c",c);
    }
    return 0;
}

复杂度

需要输出 H×WH \times W 个字符,时间复杂度为 O(HW)O(HW),构造单行使用 O(W)O(W) 空间。

总结

二维图形输出通常先按“边界行、中间行”和“实心、空心”做分类。