79. Word Search

Description:

https://leetcode.com/problems/word-search/#/description

Algorithm:

main:

for each element in 2D vector

{

if (board[i][j] == word[0])

{

mark the element;

dfs(board, pos_x, pos_y, height, width, wordIdx, word);

unmark the element;

}

}

dfs:

if (wordIdx == word.size())if (wordIdx == word.size()) return true;

check the four surrounding letters

 

if (board[i][j] == word[0])

{

mark the element;

if  dfs(board, pos_x, pos_y, height, width, wordIdx + 1, word)

return true;

unmark the element;

}

Code:

Actually my algorithm is TOTALLY the same with the fastest one. However, mine takes 76ms while the fastest only takes 6ms. I optimized my code again and again and finally get the fastest. Here are all my codes and i will show the improvements.

Code1 (76ms, beats 17.34%):

Code2 (16ms, beats 64.74%):

Main change from Code1 to Code2 is the usage of newPos_x and newPos_y

Code3 (6ms, beats 99.61%):

Main change from Code2 to Code3 is to use string &word instead of string word.

Leave a Reply

Your email address will not be published. Required fields are marked *