|
| 1 | +/* |
| 2 | +input : m x n matrix and string word |
| 3 | +output : return true if given word can be constructed |
| 4 | +
|
| 5 | +solution 1) brute force |
| 6 | +tc : O(n * 4^k) when n is the number of cells, k is the length of word |
| 7 | +sc : O(k) call stack |
| 8 | + */ |
| 9 | +class Solution { |
| 10 | + private int[][] directions = new int[][] {{-1,0}, {1,0}, {0,1}, {0,-1}}; |
| 11 | + public boolean exist(char[][] board, String word) { |
| 12 | + //edge case |
| 13 | + int m = board.length; |
| 14 | + int n = board[0].length; |
| 15 | + |
| 16 | + if(m * n < word.length()) return false; |
| 17 | + |
| 18 | + |
| 19 | + //look for the starting letter and do dfs |
| 20 | + for(int i = 0; i < m; i++) { |
| 21 | + |
| 22 | + for(int j = 0; j < n; j++) { |
| 23 | + |
| 24 | + if(board[i][j] == word.charAt(0)) { |
| 25 | + //do dfs and get answer |
| 26 | + board[i][j] = '0'; |
| 27 | + boolean res = dfsHelper(board, word, i, j, 1); |
| 28 | + board[i][j] = word.charAt(0); |
| 29 | + if(res) return true; |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + public boolean dfsHelper(char[][] board, String word, int curR, int curC, int curP) { |
| 38 | + |
| 39 | + //endclause |
| 40 | + if(curP == word.length()) return true; |
| 41 | + |
| 42 | + boolean ret = false; |
| 43 | + |
| 44 | + for(int[] direction : directions) { |
| 45 | + int nextR = curR + direction[0]; |
| 46 | + int nextC = curC + direction[1]; |
| 47 | + |
| 48 | + if(nextR < 0 || nextR >= board.length || nextC < 0 || nextC >= board[0].length) continue; |
| 49 | + |
| 50 | + if(board[nextR][nextC] == word.charAt(curP)) { |
| 51 | + board[nextR][nextC] = '0'; |
| 52 | + ret = ret || dfsHelper(board, word, nextR, nextC, curP + 1); |
| 53 | + board[nextR][nextC] = word.charAt(curP); |
| 54 | + } |
| 55 | + } |
| 56 | + return ret; |
| 57 | + } |
| 58 | +} |
0 commit comments