leetcode: Word Search

Problem Description:

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 cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =


word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.


Solution and Precautions:

The algorithm is to use DFS and Pruning to search through the whole solution space. For example, take the case in the description as our example, basically we go to every possible string in that matrix to check if it is the same as the given target string, like if the target is ABCCED, then we start from the the left top most character A, yes, it matched with the first character in the target, ok, we then test the second chracter, the next could be B or S which is neighbor to A, we got B, for B, the next could be F or C, we of course to the C, for C then next, could be C or E, we go to C, now we already matched ABCC, For next, we could choose F, C, E, S, which are neighbor to C, we then go to E, then next would be the last character D.

Written on May 20, 2013