0% found this document useful (0 votes)
16 views1 page

Word Search

Uploaded by

himalayas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views1 page

Word Search

Uploaded by

himalayas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

6.

Word Search
Medium
Given an m x n grid of characters board and a string word , return true if word exists in the
grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells
are horizontally or vertically neighboring. The same letter cell may not be used more than
once.

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

private boolean backtrack(char[][] board, String word, int idx, int i, int j,
boolean[][] visited) {
if (idx == word.length()) return true;

if (i < 0 || i >= board.length || j >= board[0].length || j < 0 ||


visited[i][j] || word.charAt(idx) != board[i][j]) {
return false;
}

visited[i][j] = true;
boolean found = backtrack(board, word, idx + 1, i + 1, j, visited) ||
backtrack(board, word, idx + 1, i, j + 1, visited) ||
backtrack(board, word, idx + 1, i - 1, j, visited) ||
backtrack(board, word, idx + 1, i, j - 1, visited);

visited[i][j] = false;
return found;
}
}
Time Complexity : O(M * N * 4^L) | Space Complexity : O(M * N)
Runtime 141ms | Beats 68.05%

You might also like