1. class Solution {
    2. public:
    3. bool check(vector<vector<char>>& board,vector<vector<int>>& temp,string word,int i,int j,int k){
    4. //若选择起点和字母第一个不相同,则返回false
    5. if(board[i][j]!=word[k]){
    6. return false;
    7. }
    8. //若对比完所有的字符找到正确的路线,则返回true
    9. else if(k==word.size()-1){
    10. return true;
    11. }
    12. //对要选择的路线进行标记
    13. temp[i][j]=true;
    14. bool result=false;
    15. //方向
    16. vector<pair<int,int>>dection{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    17. for(const auto& dec:dection){
    18. int newi=i+dec.first;
    19. int newj=j+dec.second;
    20. if(newi>=0&&newi<board.size()&&newj>=0&&newj<board[0].size()){
    21. if(!temp[newi][newj]){
    22. //如果返回值为true则直接返回true退出循环
    23. bool chec=check(board,temp,word,newi,newj,k+1);
    24. if(chec){
    25. result=true;
    26. break;
    27. }
    28. }
    29. }
    30. }
    31. temp[i][j]=false;//回溯,若所走的路线不符合要求则返回,同时要将之前的true标为false
    32. return result;
    33. }
    34. bool exist(vector<vector<char>>& board, string word) {
    35. int h=board.size();
    36. int w=board[0].size();
    37. vector<vector<int>>temp(h,vector<int>(w));
    38. //1、找到起点与第一个字母相同的起点
    39. for(int i=0;i<h;i++){
    40. for(int j=0;j<w;j++){
    41. bool result=check(board,temp,word,i,j,0);
    42. if(result){
    43. return true;
    44. }
    45. }
    46. }
    47. return false;
    48. }
    49. };