Backtracking Flashcards
1
Q
- Word Search
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.
Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
TC:
SC:
A
Takeaways:-
- Try to avoid using visited array to improve the performance
- Instead of using charAt function again and again, convert input string to a charArray and then access the characters using array index.
- Test for invalid variables as very first statement of recursive function (this will avoid the separate handling of backtracking of initial indexes) and then base case and then processing of logic.
- To avoid time limit exceed issue, Instead of using StringBuilder and checking result string in very end, use index for result string and proceed to the current recursion path only if current character in board match with current index of input string.
Pseudo Code:-