|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class Solution { |
| 4 | + |
| 5 | + private int[][] board; |
| 6 | + |
| 7 | + public int solution(int[][] rectangle, int characterX, int characterY, int itemX, int itemY) { |
| 8 | + int len = rectangle.length; |
| 9 | + board = new int[101][101]; |
| 10 | + |
| 11 | + // 좌표를 두 배로 확대해서 도형의 테두리 공간을 만든다 |
| 12 | + for(int i=0; i<len; i++) { |
| 13 | + int x1 = rectangle[i][0] * 2; |
| 14 | + int y1 = rectangle[i][1] * 2; |
| 15 | + int x2 = rectangle[i][2] * 2; |
| 16 | + int y2 = rectangle[i][3] * 2; |
| 17 | + |
| 18 | + // 좌표*2 도형 내부를 1로 채우기 |
| 19 | + for(int j=y1; j<=y2; j++) { |
| 20 | + for(int k=x1; k<=x2; k++) { |
| 21 | + board[j][k] = 1; |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + for(int i=0; i<len; i++) { |
| 27 | + int x1 = rectangle[i][0] * 2; |
| 28 | + int y1 = rectangle[i][1] * 2; |
| 29 | + int x2 = rectangle[i][2] * 2; |
| 30 | + int y2 = rectangle[i][3] * 2; |
| 31 | + |
| 32 | + // 도형의 테두리만 남기고 나머지를 0으로 채우기 |
| 33 | + for(int j=y1+1; j<=y2-1; j++) { |
| 34 | + for(int k=x1+1; k<=x2-1; k++) { |
| 35 | + board[j][k] = 0; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + int result = bfs(rectangle, characterX*2, characterY*2, itemX*2, itemY*2); |
| 40 | + return result/2; |
| 41 | + } |
| 42 | + |
| 43 | + public int bfs(int[][] rectangle, int characterW, int characterH, int itemW, int itemH) { |
| 44 | + int[] dh = {0, 1, 0, -1}; |
| 45 | + int[] dw = {-1, 0, 1, 0}; |
| 46 | + int[][] visited = new int[101][101]; |
| 47 | + |
| 48 | + Queue<int[]> q = new LinkedList<>(); |
| 49 | + q.offer(new int[]{characterH, characterW}); |
| 50 | + while(!q.isEmpty()) { |
| 51 | + int h = q.peek()[0]; |
| 52 | + int w = q.peek()[1]; |
| 53 | + q.poll(); |
| 54 | + |
| 55 | + if(h == itemH && w == itemW) { |
| 56 | + return visited[h][w]; |
| 57 | + } |
| 58 | + |
| 59 | + for(int i=0; i<4; i++) { |
| 60 | + int nextH = h + dh[i]; |
| 61 | + int nextW = w + dw[i]; |
| 62 | + if(nextH >= 0 && nextH <= 100 && nextW >= 0 && nextW <= 100) { |
| 63 | + if(visited[nextH][nextW] == 0 && board[nextH][nextW] == 1) { |
| 64 | + visited[nextH][nextW] = visited[h][w]+1; |
| 65 | + q.offer(new int[]{nextH, nextW}); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + return 0; |
| 71 | + } |
| 72 | +} |
0 commit comments