음 보물찾기 문제.. BFS
BFS를 사용하며 visited를 잘못써서 시간초과가 났었고, for문을 break하는걸 넣어놓고 안빼서 계속 틀렸었다.
2005년도 초등생은 BFS를 할줄 안다니.. 대단하네
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
/** | |
* BOJ 2589 보물섬 | |
* https://gist.github.com/KSH-code/ceff9760ed82ffd647570dae9349a4da | |
*/ | |
public class Main{ | |
private static int N,M; | |
private static int result = 0; | |
private static int go[] = {-1, -1, 1, 1}; | |
private static boolean map[][]; | |
public static void main(String[] args) throws IOException{ | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
String str1[] = br.readLine().split(" "); | |
N = Integer.parseInt(str1[0]); | |
M = Integer.parseInt(str1[1]); | |
map = new boolean[N][M]; | |
for(int i = 0; i<N; i++){ | |
String str2[] = br.readLine().split(""); | |
for(int j = 0; j<M; j++){ | |
map[i][j] = str2[j].equals("L"); | |
} | |
} | |
for(int i = 0; i<N; i++){ | |
for(int j = 0; j<M; j++){ | |
if(map[i][j]){ | |
BFS(i, j); | |
} | |
} | |
} | |
System.out.println(result); | |
} | |
private static void BFS(int x, int y){ | |
boolean visited[][] = new boolean[N][M]; | |
int time[][] = new int[N][M]; | |
Queue<Integer> queue = new LinkedList<>(); | |
queue.offer(x*100+y); | |
visited[x][y] = true; | |
while(!queue.isEmpty()){ | |
int poll = queue.poll(); | |
int tempX = poll / 100; | |
int tempY = poll % 100; | |
for(int i = 0; i<4; i++){ | |
int s = tempX; | |
int e = tempY; | |
if(i % 2 == 0){ | |
s += go[i]; | |
}else{ | |
e += go[i]; | |
} | |
if(s < 0 || s >= N || e < 0 || e >= M || visited[s][e] || !map[s][e]) continue; | |
visited[s][e] = true; | |
time[s][e] = time[tempX][tempY] + 1; | |
queue.offer(s * 100 + e); | |
result = Math.max(result, time[s][e]); | |
} | |
} | |
} | |
} |
'IT > 알고리즘' 카테고리의 다른 글
BOJ 2590 색종이 풀이(Olympiad > 한국정보올림피아드시․도지역본선 > 지역본선 2005 > 초등부 4번 Olympiad > 한국정보올림피아드시․도지역본선 > 지역본선 2005 > 중등부 2번) (0) | 2017.10.25 |
---|---|
BOJ 2042 구간 합 구하기 풀이 (0) | 2017.10.24 |
BOJ 12852 1로 만들기 2 풀이 (0) | 2017.10.20 |
2611 자동차경주 풀이 (Olympiad > 한국정보올림피아드시․도지역본선 > 지역본선 2004 > 중등부 5번) (0) | 2017.10.20 |
BOJ 2016 풀이 2004 (한국정보올림피아드시․도지역본선) (0) | 2017.10.19 |