1.注意题目的行列关系
2.’-’、’|’, '+'分清楚覆盖情况
3.使用dfs会爆内存,只有90分,使用队列就行了
import java.io.BufferedInputStream;
import java.util.*;
public class Main{
static int[] xArr = {0, 0, 1, -1};
static int[] yArr = {1, -1, 0, 0};
static int m;
static int n;
static char[][] arr;
public static void main(String[] args) {
Scanner input = new Scanner(new BufferedInputStream(System.in));
m = input.nextInt();
n = input.nextInt();
int p = input.nextInt();
input.nextLine();
arr = new char[n][m];
for (int i = 0; i < n; i++){
Arrays.fill(arr[i], '.');
}
for (int i = 0; i < p; i++){
String str = input.nextLine();
String[] strs = str.split(" ");
if (strs.length == 4){
bfs(toInt(strs[2]), toInt(strs[1]), strs[3].charAt(0), new boolean[n][m]);
} else {
link(toInt(strs[2]), toInt(strs[1]), toInt(strs[4]), toInt(strs[3]));
}
}
print();
input.close();
}
public static int toInt(String s){
return Integer.parseInt(s);
}
/**
* 如果长度为3,进行填充,此方法会爆内存,只有90分
* @param x 起始的横坐标
* @param y 起始的纵坐标
* @param c 填充用的字符
*/
/*public static void dfs(int x, int y, char c, boolean[][] used){
if (arr[x][y] == '-' || arr[x][y] == '|' || arr[x][y] == '+'){
return;
}
arr[x][y] = c;
used[x][y] = true;
for (int i = 0; i < 4; i++){
int newX = x + xArr[i];
int newY = y + yArr[i];
if (newX >= 0 && newX < n && newY >= 0 && newY < m && !used[newX][newY]){
dfs(newX, newY, c, used);
}
}
}*/
/**
* 进行填充
* @param x
* @param y
* @param c
* @param used
*/
public static void bfs(int x, int y, char c, boolean[][] used){
Deque<int[]> queue = new LinkedList<>();
queue.offer(new int[]{x, y});
used[x][y] = true;
arr[x][y] = c;
while (!queue.isEmpty()){
for (int i = queue.size(); i > 0; i--){
int[] cur = queue.poll();
for (int j = 0; j < 4; j++){
int newX = cur[0] + xArr[j];
int newY = cur[1] + yArr[j];
if (newX >= 0 && newX < n && newY >= 0 && newY < m && !used[newX][newY] &&
!(arr[newX][newY] == '-' || arr[newX][newY] == '|' || arr[newX][newY] == '+')){
arr[newX][newY] = c;
used[newX][newY] = true;
queue.offer(new int[]{newX, newY});
}
}
}
}
}
/**
* 画线
* @param x1
* @param y1
* @param x2
* @param y2
*/
public static void link(int x1, int y1, int x2, int y2){
if (x1 == x2){
for (int i = Math.min(y1, y2); i <= Math.max(y1, y2); i++){
arr[x1][i] = (arr[x1][i] == '|' || arr[x1][i] == '+') ? '+' : '-';
}
} else {
for (int i = Math.min(x1, x2); i <= Math.max(x1, x2); i++){
arr[i][y1] = (arr[i][y1] == '-' || arr[i][y1] == '+') ? '+' : '|';
}
}
}
public static void print(){
for (int i = n - 1; i >= 0; i--){
for (int j = 0; j < m; j++){
System.out.print(arr[i][j]);
}
System.out.println();
}
}
}
本文介绍了一种在二维网格上进行绘图和填充的算法实现,通过使用队列而非深度优先搜索避免了内存溢出的问题,确保了在大规模网格上的稳定运行。文章详细解释了如何处理行列关系,正确区分不同符号的覆盖情况,并提供了完整的Java代码示例。
1616

被折叠的 条评论
为什么被折叠?



