CCF-201512-3-畫圖
阿新 • • 發佈:2018-12-01
這題搞字元藝術,模擬平時畫圖那樣畫線然後填充顏色。垂直線與水平線相交點變‘+’加號,填充用廣搜,用深搜也行,不過最後一個用例會爆棧,導致執行出錯。廣搜我自己測試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()