Skip to content
the poor coder

Leetcode - Word Search Solution

Poor Man
Published
Updated
Reading time
2 min read

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.

Note: There will be some test cases with a board or a word larger than constraints to test if your solution is using pruning.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

Solution in python#

Python
class Solution(object):
  def exist(self, board, word):
      board = board
      word = word
      def ExistCharacter(i,j,index,word):
        if (i < 0 or i >= len(board) or j < 0 or j >= len(board[i])) :
            return False   

        # when index character does not match  
        if(board[i][j] != word[index])  :
            return False   

        # when completely matched  
        if(index == len(word) - 1)  :
            return True  
        # mark the current character  
        board[i][j] = '#'  

        # check every direction  
        found = ExistCharacter(i, j - 1, index + 1, word) or ExistCharacter(i, j + 1, index + 1, word) or ExistCharacter(i - 1, j, index + 1, word) or  ExistCharacter(i + 1, j, index + 1, word)  

        # unmark the current character  
        board[i][j] = word[index]  
        return found
      if (word == ""): 
          return False   

      # iterate over the board  
      for i in range(len(board)):
          for j in range(len(board[0])):
              if (ExistCharacter(i, j, 0, word)): 
                  return True   

      return False  

Keep going

2021

Leetcode - Subsets Solution

Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Example 2: Constraints: 1 <=…

2021

Leetcode - Find the Highest Altitude Solution

There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. You are given an integer array gain of length n where…

leetcodearray1 min read
ESC