|
| 1 | +/* |
| 2 | + Problem: https://leetcode.com/problems/word-search/ |
| 3 | + Description: return true if word exists in the grid |
| 4 | + Concept: Array, String, Backtracking, Matrix |
| 5 | + Time Complexity: O(MN4ᵀ), Runtime 147ms |
| 6 | + Space Complexity: O(MN), Memory 42.11MB |
| 7 | +*/ |
| 8 | +class Solution { |
| 9 | + public char[][] board; |
| 10 | + public String word; |
| 11 | + public boolean[][] visited; |
| 12 | + public int n, m; |
| 13 | + |
| 14 | + public boolean exist(char[][] board, String word) { |
| 15 | + this.board = board; |
| 16 | + this.word = word; |
| 17 | + this.m = board.length; |
| 18 | + this.n = board[0].length; |
| 19 | + this.visited = new boolean[m][n]; |
| 20 | + |
| 21 | + for(int i=0; i<m; i++){ |
| 22 | + for(int j=0; j<n; j++){ |
| 23 | + if(word.charAt(0) != board[i][j]) continue; |
| 24 | + if(wordExists(i, j, 1)) return true; |
| 25 | + } |
| 26 | + } |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + public int[] dr = new int[]{-1,1,0,0}; |
| 31 | + public int[] dc = new int[]{0,0,-1,1}; |
| 32 | + public boolean wordExists(int cr, int cc, int i){ |
| 33 | + if(i==word.length()) return true; |
| 34 | + |
| 35 | + visited[cr][cc] = true; |
| 36 | + for(int k=0; k<4; k++){ |
| 37 | + int nr = cr+dr[k]; |
| 38 | + int nc = cc+dc[k]; |
| 39 | + if(nr<0||nc<0||nr>m-1||nc>n-1||visited[nr][nc]) continue; |
| 40 | + if(board[nr][nc]!=word.charAt(i)) continue; |
| 41 | + if(wordExists(nr, nc, i+1)) return true; |
| 42 | + } |
| 43 | + visited[cr][cc] = false; |
| 44 | + |
| 45 | + return false; |
| 46 | + } |
| 47 | +} |
0 commit comments