티스토리 뷰
출저 : https://www.acmicpc.net/problem/7576
"단순 BFS"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { static int N,M; static int[][] map; static int[] dx = {0,0,1,-1}; static int[] dy = {1,-1,0,0}; static Queue<Node> q = new LinkedList<>(); static int day; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); M = Integer.parseInt(st.nextToken()); N = Integer.parseInt(st.nextToken()); map = new int[N][M]; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < M; j++) { int temp = Integer.parseInt(st.nextToken()); map[i][j] = temp; if(temp == 1) { q.add(new Node(i, j)); } } } while(!q.isEmpty()) { int size = q.size(); for (int s = 0; s < size; s++) { Node cur = q.poll(); for (int i = 0; i < 4; i++) { int nx = cur.x + dx[i]; int ny = cur.y + dy[i]; if(!isRange(nx, ny) || map[nx][ny] != 0) continue; map[nx][ny] = 1; q.add(new Node(nx, ny)); } } day++; } System.out.println(check() ? day-1: -1); } static boolean check() { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if(map[i][j] == 0) return false; } } return true; } static boolean isRange(int x , int y) { if(x < 0 || x >= N || y < 0 || y >= M) return false; return true; } } class Node { int x; int y; Node( int x, int y ) { this.x = x; this.y = y; } } | cs |
'Study > 알고리즘 문제풀이' 카테고리의 다른 글
백준 8911. 거북이 :: 돼지개발자 (0) | 2018.12.04 |
---|---|
백준 6987. 월드컵 :: 돼지개발자 (0) | 2018.12.03 |
백준 1697. 숨바꼭질 :: 돼지개발자 (0) | 2018.12.03 |
백준 4179. 불! :: 돼지개발자 (0) | 2018.12.03 |
백준 2667. 단지번호붙이기 :: 돼지개발자 (0) | 2018.12.03 |
댓글
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday