2 solutions
-
1
洪水填充
这道题依旧十分的“简单”
虽然作者是刚学OI的蒟蒻,但是我也要用蒟蒻的声音大声喊出:“我太菜了!”
题目大意
你有一个二维字符数组和查询起点,你需要把查询起点的那一段的连通块(即字母相同的一段二维区间)替换成题目给你的new_color
解题思路
依旧太“简单了”
骗你的,就是有亿点点的肝罢了
依旧仅需定义和输入+bfs搜索+输出
定义和输入
需要结构体node,用于存储坐标
需要char类型的输入时的矩阵和替换new_color前的字符和替换后的字符
需要int类型的n、m、标记数组、偏移数组
需要node类型的查询起点坐标
输入就不说了😃
bfs搜索
依旧普通优先队列bfs
由于比较模板所以仅从偏移说起
先看代码:
for(int f=0;f<4;f++){ int xx=cur.x+dx[f],yy=cur.y+dy[f]; if(xx<=n&&xx>=1&&yy<=m&&yy>=1&&!vis[xx][yy]&&c[xx][yy]==t){ vis[xx][yy]=1; c[xx][yy]=rp; que.push({xx,yy}); } }-
xx:偏移后的cur的x坐标
-
yy:偏移后的cur的y坐标
-
判断条件:
-
xx<=n&&xx>=1&&yy<=m&&yy>=1判断是否越界 -
!vis[xx][yy]判断是否走过 -
c[xx][yy]==t图上的这个位置仅能为起点坐标的同一颜色
-
-
如果条件成立
-
vis[xx][yy]=1;标记为1 -
c[xx][yy]=rp;替换图上颜色 -
que.push({xx,yy});添加至队列
-
输出
嵌套循环输出完事~
题目正解
我绝对不会告诉你我交了四次才过😭系统提示:
-
题目说的偏移是4方向
-
如果循环从1开始的话,读入题目坐标要+1
#include<bits/stdc++.h> using namespace std; const int N=110; struct node{ int x,y; }; char c[N][N],rp,t; int n,m,vis[N][N]; int dx[4]={1,-1,0,0}; int dy[4]={0,0,1,-1}; void bfs(node u){ queue<node> que; que.push(u); vis[u.x][u.y]=1; while(!que.empty()){ node cur=que.front(); que.pop(); for(int f=0;f<4;f++){ int xx=cur.x+dx[f],yy=cur.y+dy[f]; if(xx<=n&&xx>=1&&yy<=m&&yy>=1&&!vis[xx][yy]&&c[xx][yy]==t){ vis[xx][yy]=1; c[xx][yy]=rp; que.push({xx,yy}); } } } } int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>c[i][j]; } } node u; cin>>u.x>>u.y>>rp; u.x++,u.y++; t=c[u.x][u.y]; bfs(u); c[u.x][u.y]=rp; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cout<<c[i][j]<<" "; } cout<<endl; } return 0; }完结撒花!祝所有为题解点赞的人rp++
-
-
0
C++ :
#include<bits/stdc++.h> using namespace std; int ROWS = 8; int COLS = 8; char image[105][105]; struct Point { int r, c; Point(int r, int c): r(r), c(c) {} }; bool is_valid(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 && image[r][c] == prev_color && image[r][c] != new_color); } void flood_fill(Point cur, int new_color) { queue<Point> queue; queue.push(cur); int prev_color = image[cur.r][cur.c]; image[cur.r][cur.c] = new_color; while (!queue.empty()) { Point pt = queue.front (); queue.pop (); Point points[4] = {Point(pt.r+1,pt.c), Point(pt.r - 1, pt.c), Point(pt.r, pt.c + 1), Point(pt.r, pt.c - 1)}; for (auto p : points) { if (is_valid(p, prev_color, new_color)) { image[p.r][p.c] = new_color; queue.push(p); } } } } int main() { cin >> ROWS >> COLS; for (int i = 0;i<ROWS;i++){ for (int j = 0;j<COLS;j++){ cin >> image[i][j]; } } int x,y; cin >> x >> y; Point cur(x, y); char new_color = 'y'; cin >> new_color; flood_fill(cur, new_color); for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { cout << image[r][c] << ' '; } cout << endl; } return 0; }
- 1
Information
- ID
- 215
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- 10
- Tags
- # Submissions
- 4
- Accepted
- 2
- Uploaded By