深搜会爆栈的一道题(90分),宽搜可以过(100分)
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
static int N = 120,m,n;
static char a[][] = new char[N][N];
static int dx[] = {0,0,1,-1};
static int dy[] = {1,-1,0,0};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
m = scanner.nextInt();
n = scanner.nextInt();
for(int i = 0; i < n;i++) {
for(int j = 0 ; j < m ;j ++) {
a[i][j] = '.';
}
}
int q = scanner.nextInt();
while(q-->0) {
int c = scanner.nextInt();
if(c==1) {//填充操作
int x = scanner.nextInt();
int y = scanner.nextInt();
char t = scanner.next().charAt(0);
// dfs(y,x,t);
bfs(y,x,t);
}else {//划线操作
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
if(x1==x2) {//画竖线
line1(x1,y1,y2);
}else {//画横线
line2(y1,x1,x2);
}
}
}
for(int i = n-1; i >= 0 ;i--) {
for(int j = 0; j < m;j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
private static void bfs(int u, int v, char t) {
LinkedList q = new LinkedList<>();
q.add(new int[] {u,v});
a[u][v] = t;
while(!q.isEmpty()) {
int[] h = q.poll();
for(int i = 0 ; i < 4;i++) {
int x = h[0]+dx[i],y = h[1]+dy[i];
if(x>=0&&y>=0&&x
a[x][y] = t;
q.add(new int[] {x,y});
}
}
}
}
private static void line2(int y1, int x1, int x2) {
int s = Math.min(x1, x2);
int e = Math.max(x1, x2);
for(int i = s ; i <= e; i ++) {
if(a[y1][i]!='+')
a[y1][i] = a[y1][i]=='|'?'+':'-';
}
}
private static void line1(int x1, int y1, int y2) {
int s = Math.min(y1, y2);
int e = Math.max(y1, y2);
for(int i = s; i <= e; i++) {
if(a[i][x1]!='+')
a[i][x1] = a[i][x1]=='-'?'+':'|';
}
}
}
深搜代码
private static void dfs(int u, int v, char t) {
a[u][v] = t;
for(int i = 0 ; i < 4;i++) {
int x = u+dx[i],y = v+dy[i];
if(x>=0&&y>=0&&x
dfs(x,y,t);
}
}
}