From b5568e66664858cbf3b6b67fb2bd9b138359e55c Mon Sep 17 00:00:00 2001 From: Nikitha Reddy Date: Wed, 12 Feb 2025 18:17:21 +0530 Subject: [PATCH] Update WordSearch79.java --- src/WordSearch79.java | 124 +++++++----------------------------------- 1 file changed, 19 insertions(+), 105 deletions(-) diff --git a/src/WordSearch79.java b/src/WordSearch79.java index 87221d3..ef83ad4 100644 --- a/src/WordSearch79.java +++ b/src/WordSearch79.java @@ -20,116 +20,30 @@ */ -public class WordSearch79 { - public boolean exist(char[][] board, String word) { - - if (word.length() == 0) { - return true; - } - - if (board.length == 0) { - return false; - } - - int m = board.length; - int n = board[0].length; - - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - boolean[][] visited = new boolean[m][n]; - if (helper(i, j, 0, board, word, visited)) { - return true; - } - } - } - - return false; - - } - - - private boolean helper(int i, int j, int index, char[][] board, String word, boolean[][] visited) { - if (index >= word.length()) { - return true; - } - - if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) { - return false; - } - - if (visited[i][j] || board[i][j] != word.charAt(index)) { - return false; - } - - visited[i][j] = true; - - if (helper(i, j+1, index + 1, board, word, visited) || - helper(i+1, j, index + 1, board, word, visited) || - helper(i, j-1, index + 1, board, word, visited) || - helper(i-1, j, index + 1, board, word, visited)) { - return true; - } - - visited[i][j] = false; - - return false; - } - - - /** - * https://discuss.leetcode.com/topic/7907/accepted-very-short-java-solution-no-additional-space - */ - public boolean exist2(char[][] board, String word) { - - if (word.length() == 0) { - return true; - } - - if (board.length == 0) { - return false; - } - - int m = board.length; - int n = board[0].length; - - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (helper(i, j, 0, board, word)) { +Class Solution{ + public boolean exist(char board[][],String word){ + for(int i=0;i= word.length()) { - return true; - } - - if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) { - return false; - } - - if (board[i][j] != word.charAt(index)) { - return false; - } - - board[i][j] ^= 256; - - if (helper(i, j+1, index + 1, board, word) || - helper(i+1, j, index + 1, board, word) || - helper(i, j-1, index + 1, board, word) || - helper(i-1, j, index + 1, board, word)) { - return true; - } - - board[i][j] ^= 256; - - return false; + public boolean dfs(char board[][],String word,int i,int j,int index){ + if(index==word.length())return true; + if(i<0 || i>=board.length || j<0 || j>=board.length||board[i][j]!=word.charAt(i))return false; + char temp=board[i][j]; + board[i][j]="#"; + boolean found=dfs(board,word,i-1,j,index+1)|| + dfs(board,word,i+1,j,index+1)|| + dfs(board,word,i,j-1,index+1)|| + dfs(board,word,i,j-1,index+1); + board[i][j]=temp; + return found; } - } + + +