CCF-201512-3-画图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AivenZhong/article/details/84112995

这题搞字符艺术,模拟平时画图那样画线然后填充颜色。垂直线与水平线相交点变‘+’加号,填充用广搜,用深搜也行,不过最后一个用例会爆栈,导致运行出错。广搜我自己测试100*100的矩阵,然后广搜100遍都很快,不用一秒出结果,但是提交上去只有90,最后一个用例运行超时。。。很迷。

python代码

def draw_line(x1, y1, x2, y2, matrix):
    xlen = len(matrix)
    ylen = len(matrix[0])
    # 画线
    if x1 == x2:
        for y in range(min(y1, y2), max(y1, y2) + 1):
            if matrix[x1][y] == '-' or (x1 - 1 >= 0 and matrix[x1 - 1][y] == '-') or (
                    x1 + 1 < xlen and matrix[x1 + 1][y] == '-'):
                matrix[x1][y] = '+'
            else:
                matrix[x1][y] = '|'
    elif y1 == y2:
        for x in range(min(x1, x2), max(x1, x2) + 1):
            if matrix[x][y1] == '|' or (y1 - 1 >= 0 and matrix[x][y1 - 1] == '|') or (
                    y1 + 1 < ylen and matrix[x][y1 + 1] == '|'):
                matrix[x][y1] = '+'
            else:
                matrix[x][y1] = '-'


def fill_bfs(x, y, c, matrix):
    # 填充
    xlen = len(matrix)
    ylen = len(matrix[0])
    diret = [[1, 0], [-1, 0], [0, -1], [0, 1]]
    q = []
    if 0 <= x < xlen and \
            0 <= y < ylen and \
            matrix[x][y] != '|' and \
            matrix[x][y] != '-' and \
            matrix[x][y] != '+' and \
            matrix[x][y] != c:
        q.append([x, y])
    matrix[x][y] = c
    while q:
        node = q.pop(0)
        for d in diret:
            tx, ty = node[0] + d[0], node[1] + d[1]
            if 0 <= tx < xlen and \
                    0 <= ty < ylen and \
                    matrix[tx][ty] != '|' and \
                    matrix[tx][ty] != '-' and \
                    matrix[tx][ty] != '+' and \
                    matrix[tx][ty] != c:
                q.append([tx, ty])
                matrix[tx][ty] = c


# 主程序
m, n, q = map(int, input().split())
matrix = [['.' for i in range(n)] for j in range(m)]

for i in range(q):
    op = input().split()
    if op[0] == '0':
        draw_line(int(op[1]), int(op[2]), int(op[3]), int(op[4]), matrix)
    elif op[0] == '1':
        fill_bfs(int(op[1]), int(op[2]), op[3], matrix)

# 打印顺时针翻转的图
for j in range(n)[::-1]:
    for i in range(m):
        print(matrix[i][j], end='')
    print()

猜你喜欢

转载自blog.csdn.net/AivenZhong/article/details/84112995