按行模板生成矩形:实心整行填充字符,空心只在首末行和左右两条边画字符。
OJ: roj
题目 ID: 1097
难度:入门
标签:模拟字符串一本通
创建: 2026-09-29 18:40
更新: 2026-10-05 01:01
题目描述
给定高 h w c d,输出画出的图形。
样例输入 7 7 @ 0 对应一个 7×7 的空心 @ 矩形。
思路
以"行"为枚举单位:先造出 border(border + middle × (h-2) + border 一次性输出。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 18:40
# update_at: 2026-10-04 12:56
import sys
def rectangle(height: int, width: int, ch: bytes, solid: bool) -> bytes:
"""返回矩形画布:实心每一行都是 ch;空心只在四条边上画 ch,内部填空格。"""
border = ch * width # 上下两条边,也是实心的每一行
middle = border if solid else ch + b" " * (width - 2) + ch # 空心时中间行 = 左右边框 + 空白
rows = [border] + [middle] * (height - 2) + [border] # 高度 ≥ 3,首尾两行必为实边
return b"\n".join(rows) + b"\n\n" # 末尾补一个空行,与标准程序一致
def solve() -> None:
data = iter(sys.stdin.buffer.read().split())
height, width = int(next(data)), int(next(data)) # 题面的 h、w
ch = next(data) # 填充字符
fill = next(data) == b"1" # d = 1 表示实心
sys.stdout.buffer.write(rectangle(height, width, ch, fill))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-04 22:12
* update_at: 2026-10-04 22:12
*/
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
// 输入:高度 h、宽度 w、字符 c、标志 d(0 空心 / 1 实心)
ll h, w;
char ch;
ll d;
int main() {
// 读取一行四参数
scanf("%lld %lld %c %lld", &h, &w, &ch, &d);
// border:上下两条边,也是实心的每一行;w 非负,隐式转 size_t 安全
string border;
border.append(w, ch);
// middle:实心时整行字符;空心时左右各 1 个字符 + 中间 w-2 个空格
string middle;
if (d == 1) {
middle = border;
} else {
middle.push_back(ch);
middle.append(w - 2, ' ');
middle.push_back(ch);
}
// 输出:border + middle 重复 (h-2) 次 + border,末尾空行
// 行数 = h,先全部放到 vector 里一次性打印
vector<string> rows;
rows.push_back(border);
for (ll i = 0; i < h - 2; ++i) {
rows.push_back(middle);
}
rows.push_back(border);
for (size_t i = 0; i < rows.size(); ++i) {
printf("%s\n", rows[i].c_str());
}
// 与原题样例末尾空行一致,补一行空行
printf("\n");
return 0;
}