学习C++从娃娃抓起!记录下CSP-J备考学习过程中的题目,记录每一个瞬间。
附上汇总贴:历年CSP-J初赛真题解析 | 汇总_热爱编程的通信人的博客-CSDN博客
(洪水填充)现有用字符标记像素颜色的8x8图像。颜色填充的操作描述如下:给定起始像素的位置和待填充的颜色,将起始像素和所有可达的像素(可达的定义:经过一次或多次的向上、下、左、右四个方向移动所能到达且终点和路径上所有像素的颜色都与起始像素颜色相同),替换为给定的颜色。
试补全程序。
#include <bits/stdc++.h>
using namespace std;
const int ROWS = 8;
const int COLS = 8;
struct Point {
int r, c;
Point(int r, int c): r(r), c(c) {} //构造函数
};
bool is_valid(char image[ROWS][COLS], Point pt,
int prev_color, int new_color) {
int r = pt.r;
int c = pt.c;
return (0<=r && r<ROWS && 0<=c && c<COLS && //判断r和c在图像中
①&& image[r][c] != new_color); //image[r][c]!=new_color表示颜色没有被修改过
}
void flood_fill(char image[ROWS][COLS], Point cur, int new_color) { //cur是[4,4],new_color是y
queue<Point> queue;
queue.push(cur);
int prev_color = image[cur.r][cur.c]; //prev_color = b
②;
while (!queue.empty()) {
Point pt = queue.front();
queue.pop();
Point points[4] = {③, Point(pt.r - 1, pt.c),
Point(pt.r, pt.c + 1), Point(pt.r, pt.c -1)};
for (auto p:points) { //基于范围的枚举,会从points中的4个位置依次枚举
if (is_valid(image, p, prev_color, new_color)) {
④;
⑤;
}
}
}
}
int main() {
char image[ROWS][COLS] = {
{'g','g','g','g','g','g','g','g'},
{'g','g','g','g','g','g','r','r'},
{'g','r','r','g','g','r','g','g'},
{'g','b','b','b','b','r','g','r'},
{'g','g','g','b','b','r','g','r'},
{'g','g','g','b','b','b','b','r'},
{'g','g','g','g','g','b','g','g'},
{'g','g','g','g','g','b','b','g'}};
Point cur(4, 4); //相当于cur.r=4,cur.c=4
char new_color = 'y';
flood_fill(image, cur, new_color); //将[4,4]位置的b及可达的b都换成y
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
cout << image[r][c] << " ";
}
cout << endl;
}
// 输出:
// g g g g g g g g
// g g g g g g r r
// g r r g g r g g
// g y y y y r g r
// g g g y y r g r
// g g g y y y y r
// g g g g g y g g
// g g g g g y y g
return 0;
}
40、①处应填( )
A.image[r][c] == prev_color
B.image[r][c] != prev_color
C.image[r][c] == new_color
D.image[r][c] != new_color
【答案】:A
【解析】
该位置上下左右的颜色要与原来的原色相同,才可以灌溉。所以选A
41、②处应填( )
A.image[cur.r+1][cur.c] = new_color
B.image[cur.r][cur.c] = new_color
C.image[cur.r][cur.c+1] = new_color
D.image[cur.r][cur.c] = prev_color
【答案】:B
【解析】
上一句是将之前的颜色保存至prev_color中,所以此行应该是要把新的颜色赋予当前的位置,即[cur.r][cur.c]
42、③处应填( )
A.Point(pt.r, pt.c)
B.Point(pt.r, pt.c+1)
C.Point(pt.r+1, pt.c)
D.Point(pt.r+1, pt.c+1)
【答案】:C
【解析】
通过其他三个位置变换,可以推测出此行的目的是获得原有坐标的上下左右位置
43、④处应填( )
A.prev_color = image[p.r][p.c]
B.new_color = image[p.r][p.c]
C.image[p.r][p.c] = prev_color
D.image[p.r][p.c] = new_color
【答案】:D
【解析】
如果判断该位置可以灌溉,需要把新的颜色赋值给该位置,选D
44、⑤处应填( )
A.queue.push(p)
B.queue.push(pt)
C.queue.push(cur)
D.queue.push(Point(ROWS, COLS))
【答案】:A
【解析】
需要把新的位置p放入到队列中,所以选A