Skip to content

Commit

Permalink
Time: 138 ms (68.71%), Space: 41.2 MB (93.07%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
hanull committed Aug 9, 2024
1 parent 82ad41f commit ce4b482
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions 0079-word-search/0079-word-search.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class Solution {

public boolean exist(char[][] board, String word) {
for (int i=0; i<board.length; i++) {
for (int j=0; j<board[0].length; j++) {
if (board[i][j] == word.charAt(0)) {
if (search(0, i, j, board, word, new boolean[board.length][board[0].length])) {
return true;
}
}
}
}

return false;
}

private boolean search(int index, int x, int y, char[][] board, String word, boolean[][] visited) {
if (index == word.length()) {
return true;
}

if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) {
return false;
}

if (visited[x][y]) {
return false;
}

if (board[x][y] != word.charAt(index)) {
return false;
}

visited[x][y] = true;
if (search(index + 1, x + 1, y, board, word, visited) ||
search(index + 1, x, y + 1, board, word, visited) ||
search(index + 1, x - 1, y, board, word, visited) ||
search(index + 1, x, y - 1, board, word, visited)) {
return true;
}
visited[x][y] = false;

return false;
}
}

0 comments on commit ce4b482

Please sign in to comment.