|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | + |
| 4 | +class Solution { |
| 5 | + |
| 6 | + //상,하,좌,우 |
| 7 | + static int[] dx = {0,1,-1,0}; |
| 8 | + static int[] dy = {1,0,0,-1}; |
| 9 | + |
| 10 | + static int m, n; |
| 11 | + |
| 12 | + static boolean result; //exist 함수가 호출될때마다 초기화해야함 |
| 13 | + static char[][] map; //지역변수 board 저장용 |
| 14 | + static String w; //word 저장용 |
| 15 | + public boolean exist(char[][] board, String word) { |
| 16 | + |
| 17 | + result=false; |
| 18 | + |
| 19 | + m = board.length; |
| 20 | + n = board[0].length; |
| 21 | + |
| 22 | + w = word; |
| 23 | + //map <- board |
| 24 | + map = new char[m][n]; |
| 25 | + for(int i =0; i<m;i++){ |
| 26 | + for(int j=0; j< n; j++){ |
| 27 | + map[i][j] = board[i][j]; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + |
| 32 | + for(int x =0 ; x < m; x++){ |
| 33 | + for(int y =0 ; y < n ;y++){ |
| 34 | + dfs(x, y , 0); //위치 x,y, word에 대한 찾는 인덱스 |
| 35 | + if (result) return result; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + //기본 |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private static void dfs(int x, int y, int idx){ |
| 46 | + //종료조건 |
| 47 | + if (result) return; |
| 48 | + |
| 49 | + if (!checkin(x, y) || map[x][y] != w.charAt(idx)) return; |
| 50 | + |
| 51 | + //마지막 문자일때 종료 |
| 52 | + if (idx == w.length() - 1){ |
| 53 | + result = true; |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + char temp = map[x][y]; |
| 58 | + map[x][y] = '#'; |
| 59 | + |
| 60 | + for(int i = 0; i < 4; i++){ |
| 61 | + dfs(x + dx[i], y + dy[i], idx + 1); |
| 62 | + } |
| 63 | + |
| 64 | + map[x][y] = temp; |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + //map 내부 checkin 함수 정의 |
| 69 | + private static boolean checkin(int x, int y){ |
| 70 | + return x >= 0 && x < m && y >= 0 && y < n; |
| 71 | + } |
| 72 | +} |
| 73 | + |
0 commit comments