|
| 1 | +//LeetCode 79. Word Search |
| 2 | +//Question - https://leetcode.com/problems/word-search/ |
| 3 | + |
| 4 | +class Solution { |
| 5 | + public boolean exist(char[][] board, String word) { |
| 6 | + |
| 7 | + for(int i = 0 ; i < board.length ; i++){ |
| 8 | + for(int j = 0 ; j < board[0].length ; j++){ |
| 9 | + if(helper(board, i, j, word, 0)) return true; |
| 10 | + } |
| 11 | + } |
| 12 | + return false; |
| 13 | + } |
| 14 | + |
| 15 | + public boolean helper(char[][] b, int x, int y, String s, int end){ |
| 16 | + //Base Cases |
| 17 | + if(end == s.length()) return true; |
| 18 | + |
| 19 | + if(x < 0 || x >= b.length || y < 0 || y >= b[0].length) return false; |
| 20 | + if(b[x][y] != s.charAt(end)) return false; |
| 21 | + |
| 22 | + //Mark as visited |
| 23 | + b[x][y] = '#'; |
| 24 | + |
| 25 | + //go deeper into recursion |
| 26 | + boolean res = helper(b, x+1, y, s, end+1) || |
| 27 | + helper(b, x-1, y, s, end+1) || |
| 28 | + helper(b, x, y+1, s, end+1) || |
| 29 | + helper(b, x, y-1, s, end+1); |
| 30 | + //backtarck |
| 31 | + b[x][y] = s.charAt(end); |
| 32 | + |
| 33 | + return res; |
| 34 | + } |
| 35 | +} |
0 commit comments