Happy Condition First Before Failure
We want to check the happy condition first before failure.
For example, in the case of WordSearch, with the following implementation:
class App
def searchWord(self, board, row, col, word, index, visited):
# Invalid check first
if not self.isValidCell(board, row, col, visited):
return False
# Happy check after
if index >= len(word):
return True
currentLetter = board[row][col]
if currentLetter != word[index]: return False
# ...
In here, our algorithm will only return true if it passes all the tests. That means we only return True
if index
reaches to the end of word.
However, what happen if we went through the word already but the cell is invalid? For example:
In here we're following this path: A -> B -> C -> F -> J -> H -> G
. Let's say after G
, we found the word we're looking for. However if we go after G
, the algorithm will return False
since it's an invalid index.
Therefore, we need to swap the happy scenario on top first:
class App
def searchWord(self, board, row, col, word, index, visited):
# NOTE: Happy check here first
if index >= len(word):
return True
# Invalid check after
if not self.isValidCell(board, row, col, visited):
return False
currentLetter = board[row][col]
if currentLetter != word[index]: return False
# ...