I had never dared to do this before. I did not expect that I handed it back the day before yesterday ..
At that time, why do we want to use recursion instead of dp? Because there are many situations where I want to reach a certain position, even if the search from the current position is known, but I cannot know what the previous status is. To be honest, I will not use dp to solve this problem ..
The concept of recursion is too much. Starting from the current point, there are four positions up, down, and left to test. If the test is successful, mark the current position with other symbols to avoid repeated access. Actually, it is DFS, but there are more portals.
It should be noted that each point can be used as the starting point, so this should be exhaustive, otherwise the situation will be missed. Of course, there is a situation where the result can be returned, and the result can be trimmed.
Code stinks and grows, but work:
class Solution {public: int row, column; bool doexist(vector<vector<char> > &board, string &word, int len, int i, int j){ if(len == word.length()) return true; bool res; if(i>0&&board[i-1][j] == word[len]){ board[i-1][j] = '.'; res = doexist(board, word, len+1, i-1, j); if(res) return true; else board[i-1][j] = word[len]; } if(i<row-1&&board[i+1][j] == word[len]){ board[i+1][j] = '.'; res = doexist(board, word, len+1, i+1, j); if(res) return true; else board[i+1][j] = word[len]; } if(j>0&&board[i][j-1] == word[len]){ board[i][j-1] = '.'; res = doexist(board, word, len+1, i, j-1); if(res) return true; else board[i][j-1] = word[len]; } if(j<column-1&&board[i][j+1] == word[len]){ board[i][j+1] = '.'; res = doexist(board, word, len+1, i, j+1); if(res) return true; else board[i][j+1] = word[len]; } return false; } bool exist(vector<vector<char> > &board, string word) { row = board.size(); if(row == 0) return false; column = board[0].size(); char c; for(int i=0;i<row;i++){ for(int j=0;j<column;j++){ if(board[i][j] == word[0]){ board[i][j] = '.'; if(doexist(board, word, 1, i, j)) return true; board[i][j] = word[0]; } } } return false; }};