https://www.acmicpc.net/board/view/72946
글 읽기 - 시간초과가 나는데 불필요한 코드를 알려주실 수 있나요?
댓글을 작성하려면 로그인해야 합니다.
www.acmicpc.net
※ 적으신 코드는 Visit 체크를 큐에서 꺼낼 때 합니다. 즉, 한 번 이상 꺼내기 전에는 visit 처리가 안 됩니다. 큐에 넣을 때 처리하도록 하셔야 합니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
static char[][] ch;
static boolean [][] visit;
static boolean[][] blind_visit;
static int[] x_move = {-1,1,0,0};
static int[] y_move = {0,0,-1,1};
static int N;
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
ch = new char[N][N];
visit = new boolean[N][N];
blind_visit = new boolean[N][N];
for(int i = 0; i < N; i++) {
String str = br.readLine();
for(int j = 0; j < N; j++) {
ch[i][j] = str.charAt(j);
}
}
int result = 0;
int result1 = 0;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
if(!visit[i][j]) {
bfs(i,j);
result++;
}
if(!blind_visit[i][j]) {
blind(i,j);
result1++;
}
}
}
System.out.println(result+" "+result1);
}
static void bfs(int x, int y) {
LinkedList<Node> que = new LinkedList<>();
char chr = ch[x][y];
visit[x][y] = true;
que.add(new Node(x,y));
int dis = 3;
while(!que.isEmpty()) {
Node temp = que.poll();
for(int i = 0; i < 4; i++) {
int tx = temp.x+x_move[dis];
int ty = temp.y+y_move[dis];
if(tx >= 0 && tx < N && ty >= 0 && ty < N && chr == ch[tx][ty] && !visit[tx][ty]) {
que.add(new Node(tx, ty));
visit[tx][ty] = true;
}
dis = change(dis);
}
}
}
static void blind(int x, int y) {
LinkedList<Node> que = new LinkedList<>();
char chr = ch[x][y];
boolean red = false;
if(chr == 'R' || chr == 'G') {
red = true;
}
que.add(new Node(x,y));
int dis = 3;
while(!que.isEmpty()) {
Node temp = que.poll();
blind_visit[temp.x][temp.y] = true;
for(int i = 0; i < 4; i++) {
int tx = temp.x+x_move[dis];
int ty = temp.y+y_move[dis];
if(tx >= 0 && tx < N && ty >= 0 && ty < N && !blind_visit[tx][ty]) {
if(red) {
if(ch[tx][ty] == 'R' || ch[tx][ty] == 'G') {
que.add(new Node(tx, ty));
blind_visit[tx][ty] = true;
}
}
else {
if(ch[tx][ty] == 'B') {
que.add(new Node(tx, ty));
blind_visit[tx][ty] = true;
}
}
}
dis = change(dis);
}
}
}
static int change(int n) {
if(n == 0)
return 3;
return n-1;
}
}
'백준' 카테고리의 다른 글
[백준] 16236 아기 상어 [자바] (0) | 2022.04.19 |
---|---|
[백준] 16928 뱀과 사다리 게임 [자바] (0) | 2022.04.16 |
[백준] 6064 카잉 달력 [자바] (0) | 2022.04.13 |
[백준] 1107 리모컨 [자바] (0) | 2022.04.09 |
[백준] 1074 Z [자바] (0) | 2022.03.17 |