我觉得这道题有两个难点吧,
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);
}
}