Word Search - Array - Medium - LeetCode
💻 coding

Word Search - Array - Medium - LeetCode

1 min read 283 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves finding a word in a 2D grid using adjacent cells without reusing letters.
  • 2The solution utilizes a recursive helper function to explore possible paths in the grid.
  • 3Time complexity is O(2^n) and space complexity is O(n) for the algorithm.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves finding a word in a 2D grid using adjacent cells without reusing letters."

Word Search - Array - Medium - LeetCode

Given a 2D board and a word, find if the 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.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false

Constraints:

board and word consists only of lowercase and uppercase English letters. 1 <= board.length <= 200 1 <= board[i].length <= 200 1 <= word.length <= 10^3

public class Solution {
 public bool Exist(char[][] board, string word) {
 
 var used = new HashSet<string>();
 for(int i=0;i<board.Length;i++){
 for(int j=0;j<board[0].Length;j++){
 if(board[i][j]==word[0]){ 
 var res = Helper(board,i,j, word, 0, used); 
 if(res){
 return true;
 }
 }
 }
 }
 
 return false;
 }
 
 private bool Helper(char[][] board, int x, int y, string word,int start, HashSet<string> used){
 
 if(start == word.Length && used.Count()==word.Length){ 
 return true;
 } 
 
 if(x<0 || x>board.Length-1){
 return false;
 }
 
 if(y<0 || y > board[0].Length-1){
 return false;
 }
 
 if(start> word.Length-1){
 return false;
 }
 
 if(board[x][y]!=word[start]){
 return false;
 }
 
 if(used.Contains(GetKey(x,y))){
 return false;
 }
 
 used.Add(GetKey(x,y));
 
 bool result = false; 
 
 int x1 = x-1;
 int y1 = y; 
 result = result || Helper(board, x1, y1, word, start+1, used);
 
 x1 = x+1;
 y1 = y; 
 result = result || Helper(board, x1, y1, word, start+1, used);
 
 x1 = x;
 y1 = y-1; 
 result = result || Helper(board, x1, y1, word, start+1, used);
 
 x1 = x;
 y1 = y+1; 
 result = result || Helper(board, x1, y1, word, start+1, used);
 
 used.Remove(GetKey(x, y));
 return result;
 }
 
 private string GetKey(int x, int y){
 return x+":"+y;
 }
}

Time Complexity: O(2^n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 November 2020 · 1 min read · 283 words

Part of AskGif Blog · coding

You might also like

Word Search - Array - Medium - LeetCode | AskGif Blog