201512-3 畫圖
阿新 • • 發佈:2018-12-09
我覺得這道題有兩個難點吧,
1、座標轉化,原始座標(i,j),真實座標應該轉換為(rows - j - 1, i)
2、填充操作,使用遞迴填充,遞迴出口條件時下標越界或者遇到邊界或者該位置已被填充,三個出口條件缺一不可
奉上java滿分程式碼
import java.util.*; public class Main { private static int rows, cols; private static char[][] canvas; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] firstLine = scanner.nextLine().split(" "); cols = Integer.parseInt(firstLine[0]); rows = Integer.parseInt(firstLine[1]); canvas = new char[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { canvas[i][j] = '.'; } } for (int i = 0; i < Integer.parseInt(firstLine[2]); i++) { String[] line = scanner.nextLine().split(" "); boolean drawLine = Integer.parseInt(line[0]) == 0; if (drawLine) { int sx = rows - Integer.parseInt(line[2]) - 1; int sy = Integer.parseInt(line[1]); int ex = rows - Integer.parseInt(line[4]) - 1; int ey = Integer.parseInt(line[3]); drawLine(sx, sy, ex, ey); } else { int sx = rows - Integer.parseInt(line[2]) - 1; int sy = Integer.parseInt(line[1]); fill(sx, sy, line[3].charAt(0)); } } scanner.close(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(canvas[i][j]); } System.out.println(); } } private static void drawLine(int sx, int sy, int ex, int ey) { if (sx == ex) { int start = Math.min(sy, ey); int end = Math.max(sy, ey); for (int j = start; j <= end; j++) { if (canvas[sx][j] == '+') continue; canvas[sx][j] = canvas[sx][j] == '|' ? '+' : '-'; } } else { int start = Math.min(sx, ex); int end = Math.max(sx, ex); for (int i = start; i <= end; i++) { if (canvas[i][sy] == '+') continue; canvas[i][sy] = canvas[i][sy] == '-' ? '+' : '|'; } } } private static void fill(int i, int j, char ch) { if (i < 0 || i > rows - 1 || j < 0 || j > cols - 1) return; char val = canvas[i][j]; if (val == '-' || val == '|' || val == '+' || val == ch) return; canvas[i][j] = ch; fill(i - 1, j, ch); fill(i + 1, j, ch); fill(i, j - 1, ch); fill(i, j + 1, ch); } }