-
[KOITP] 유령선자료구조 및 알고리즘/문제풀이 2017. 1. 16. 07:59
출 처 : http://koitp.org/problem/SDS_PRO_4_1/read/
시간 제한 메모리 제한 제출 횟수 정답 횟수 (비율) 정답자 수 1.0 초 512 MB 2193 378 (17%) 323 < Comment >
단순한 BFS 문제인데, 그럼에도 불구하고 예외처리를 확실히 해주지 못하는 바람에 오랜 시간이 걸렸습니다. 다른 것은 아니었고, 익셉션이 발생하던 이유는 제가 리턴 값을 count 로 주어야하는데, 이를 계속 큐에 들어있는 노드의 마지막 값으로 출력하려고 했기 때문에 생긴 문제였습니다.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.util.StringTokenizer; public class Spector { public static int W = 0; public static int H = 0; public static char[][] map = null; public static boolean[][] isVisited = null; public static int[] dx = {1, -1, 0, 0}; public static int[] dy = {0, 0, 1, -1}; public static class Node { int x = 0; int y = 0; int depth = 0; public Node(int x, int y, int depth) { this.x = x; this.y = y; this.depth = depth; } public int getX() { return x; } public int getY() { return y; } public int getDepth() { return depth; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); W = Integer.parseInt(st.nextToken()); H = Integer.parseInt(st.nextToken()); map = new char[H][W]; isVisited = new boolean[H][W]; String strLine = ""; int startx = 0; int starty = 0; for (int i = 0 ; i < H ; i++) { strLine = br.readLine(); for (int j = 0 ; j < W ; j ++) { map[i][j] = strLine.charAt(j); if (map[i][j] == 'S') { startx = i; starty = j; } } } int result = BFS(startx, starty); bw.write("" + result); bw.flush(); bw.close(); } public static int BFS (int x, int y) { ArrayDeque<Node> dq = new ArrayDeque<>(); dq.addLast(new Node(x, y, 0)); while(!dq.isEmpty()) { Node node = dq.pollFirst(); int count = node.getDepth(); if(isVisited[node.getX()][node.getY()]) continue; int nodeX = node.getX(); int nodeY = node.getY(); isVisited[nodeX][nodeY] = true; for (int i = 0 ; i < 4 ; i++) { int nx = nodeX + dx[i]; int ny = nodeY + dy[i]; if (nx < H && nx >= 0 && ny < W && ny >= 0) { if (map[nx][ny] == 'O') { dq.addLast(new Node(nx, ny, count + 1)); } else if (map[nx][ny] == 'E') { return dq.isEmpty() ? 1 : count + 1; } } } } return -1; } }