Word Search Using Backtracking Algorithm

Introduction

 
We all have played Word Search but what if we build a code which would actually search a word and return whether it exists or not? This can be achieved by one very simple and elegant algorithmic technique known as the backtracking algorithm. We choose the backtracking algorithm because it's deterministic and goes in a depth-first order, at each level we can edit information, which keeps the state of our system the way we need it to for the next level's recursive calls, and then we can undo the change we made for whenever we go back up to the previous level. In short, we can have shared variable without having to create a new one for each recursive call which in turn, saves time as well as memory. So in this article we will discuss how to search a given word in a given N x N board using the backtracking algorithm.
 

Problem Statement

 
Given a 2D board of characters and a word to search, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Given below are the sample inputs and their outputs respectively for the problem. For more details, here is the link to the leetcode question.
  1. static void Main(string[] args)  
  2. {  
  3.     var game = new WordSearch(new List<List<char>>{  
  4.         new List<char>{'A''B''C''E'},  
  5.         new List<char>{'S''F''C''S'},  
  6.         new List<char>{'A''D''E''E'}  
  7.     });  
  8.     var result = game.Exist("ABCCED"); // true  
  9.     result = game.Exist("SEE"); // true  
  10.     result = game.Exist("ABCB"); // false  
  11. }  

Solution

 
We are allowed to start from any block in the board, can only travel to adjacent (i.e., up, down, left & right) blocks and cannot reuse any block. Considering these three conditions as our golden rules now we will construct our algorithm by iterating over every block in the board and in each iteration we will perform the following,
  1. Check if the block is valid, as in whether it's out of bounds or whether the searching word has the character or not.
  2. Mark the current block with any other character which manages the 3rd golden rule of the problem (cannot reuse any block), we have used '#'.
  3. Now we will recursively check the left, right, up and down blocks to match the next character of the searching word.
  4. Unmark the block which we had marked in step 2.
  5. Return true if this block was the end of the word or else any of the recursive calls returned true.
So here is the C# code for the solution to this problem,
  1. class WordSearch  
  2. {  
  3.     private readonly List<List<char>> Board;  
  4.     public WordSearch(List<List<char>> board)  
  5.     {  
  6.         this.Board = board;  
  7.     }  
  8.     private bool ExistCharacter(int i, int j, int searchIndex, string searchWord)  
  9.     {  
  10.         // when reached outside the board  
  11.         if (i< 0 || i >= Board.Count || j< 0 || j >= Board[i].Count)  
  12.             return false;   
  13.           
  14.         // when index character does not match  
  15.         if(Board[i][j] != searchWord[searchIndex])  
  16.             return false;   
  17.           
  18.         // when completely matched  
  19.         if(searchIndex == searchWord.Length - 1)  
  20.             return true;  
  21.   
  22.         // mark the current character  
  23.         Board[i][j] = '#';  
  24.           
  25.         // check every direction  
  26.         bool found = ExistCharacter(i, j - 1, searchIndex + 1, searchWord) ||  
  27.             ExistCharacter(i, j + 1, searchIndex + 1, searchWord) ||  
  28.             ExistCharacter(i - 1, j, searchIndex + 1, searchWord) ||  
  29.             ExistCharacter(i + 1, j, searchIndex + 1, searchWord);  
  30.   
  31.         // unmark the current character  
  32.         Board[i][j] = searchWord[searchIndex];  
  33.         return found;  
  34.     }  
  35.     public bool Exist(string searchWord)  
  36.     {  
  37.         if (searchWord == "")  
  38.             return false;   
  39.   
  40.         // iterate over the board  
  41.         for (int i = 0; i < Board.Count; i++)  
  42.         {  
  43.             for (int j = 0; j < Board[i].Count; j++)  
  44.             {  
  45.                 // check first character  
  46.                 if (ExistCharacter(i, j, 0, searchWord))  
  47.                     return true;   
  48.             }  
  49.         }  
  50.         return false;  
  51.     }  
  52. }  


Similar Articles