问题描述
Sample Input-1
4 2 3
1 0 0 B
0 1 0 2 0
1 0 0 A
Sample Output-1
AAAA
A--A
Sample Input-2
16 13 9
0 3 1 12 1
0 12 1 12 3
0 12 3 6 3
0 6 3 6 9
0 6 9 12 9
0 12 9 12 11
0 12 11 3 11
0 3 11 3 1
1 4 2 C
Sample Output-2
................
...+--------+...
...|CCCCCCCC|...
...|CC+-----+...
...|CC|.........
...|CC|.........
...|CC|.........
...|CC|.........
...|CC|.........
...|CC+-----+...
...|CCCCCCCC|...
...+--------+...
................
解题思路以及关键代码
本题就是一道常规的bfs/dfs的题,需要注意的是在进行填充的时候(也就是bfs/dfs判断是否合法的时候)需要注意 填充不能触及线段并且超过边界。
这里线段部分用了vis[ ][ ]数组进行标示。
其次还有一个注意的点是,画布的左下角是坐标为 (0, 0) 的位置,向右为x坐标增大的方向,向上为y坐标增大的方向。
我习惯a[x][y]来表示 为了调节 传入函数的参数 x与y的位置相反
void line(int y1, int x1, int y2, int x2)
全部代码
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int maxn = 105;
char a[maxn][maxn];
bool vis[maxn][maxn] = { 0 };
bool v[maxn][maxn] = { 0 };
int m, n, p;
struct point
{
int y;
int x;
point()
{
x = -1;
y = -1;
}
point(int y, int x)
{
this->y = y;
this->x = x;
}
};
const int dy[4] = { 0,0,1,-1 };
const int dx[4] = { 1,-1,0,0 };
void line(int y1, int x1, int y2, int x2)
{
if (x1 == x2)
{
if (y2 > y1)
swap(y2, y1);
if (y1 > y2)
{
for (int i = y2; i <= y1; i++)
{
if (a[x1][i] == '|' || a[x1][i] == '+')
a[x1][i] = '+', vis[x1][i] = 1;
else
a[x1][i] = '-', vis[x1][i] = 1;
}
}
}
else
{
if (x2 > x1)
swap(x2, x1);
if (x1 > x2)
{
for (int i = x2; i <= x1; i++)
{
if (a[i][y1] == '-' || a[i][y1] == '+')
a[i][y1] = '+', vis[i][y1] = 1;
else
a[i][y1] = '|', vis[i][y1] = 1;
}
}
}
}
void fill(int y, int x, char c)
{
memset(v, 0, sizeof(v));
queue<point> q;
point now(y, x);
point after;
q.push(now);
v[x][y] = 1;
a[x][y] = c;
while (!q.empty())
{
now = q.front(); q.pop();
for (int i = 0; i < 4; i++)
{
int new_y = now.y + dy[i],
new_x = now.x + dx[i];
if (new_x >= 0 && new_x < n && new_y >= 0 && new_y < m && !vis[new_x][new_y] && !v[new_x][new_y])
{
v[new_x][new_y] = 1;
a[new_x][new_y] = c;
after.x = new_x, after.y = new_y;
q.push(after);
}
}
}
}
int main()
{
memset(a, '.', sizeof(a));
memset(vis, 0, sizeof(vis));
cin >> m >> n >> p; //数组 a[n][m]
int choice, y1, x1, y2, x2;
char c;
while (p--)
{
cin >> choice;
if (choice == 0)
{
cin >> y1 >> x1 >> y2 >> x2;
line(y1, x1, y2, x2);
}
else
{
cin >> y1 >> x1 >> c;
fill(y1, x1, c);
}
}
for (int i = n-1; i >= 0; i--)
{
for (int j = 0; j < m; j++)
cout << a[i][j];
cout << endl;
}
return 0;
}