leetcode_word_search 发表于 2016-12-05 难度:Medium 解题思路:深度优先遍历。如果某个字符串匹配,则对它的上、下、左、右分别进行递归,同时将匹配的字符串辨识成”*”,防止重复,递归好之后,要记得还原。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051class Solution {public: bool exist(vector<vector<char>>& board, string word) { bool ret; for(int i = 0; i < board.size(); i++) { for(int j = 0; j < board[0].size(); j++) { ret = search_char(board,i,j,word,0); if(ret ==true) return ret; } } return false; } bool search_char(vector<vector<char>>& board, int i, int j, string word, int word_index) { if(i < 0 || i >= board.size()) return false; if(j < 0 || j >= board[0].size()) return false; // cout<<"find: "<<board[i][j]<<endl; if(word[word_index] != board[i][j]) { return false; } else { char ch = board[i][j]; board[i][j] = '$'; bool ret = true; if(word_index+1 == word.size()) return ret; ret = ret && search_char(board, i-1,j,word,word_index+1); if(ret == true) return true; ret = true; ret = ret && search_char(board, i+1,j,word,word_index+1); if(ret == true) return true; ret = true; ret = ret && search_char(board, i,j-1,word,word_index+1); if(ret == true) return true; ret = true; ret = ret && search_char(board, i,j+1,word,word_index+1); board[i][j] = ch; return ret; } }}; 运行结果:56ms,超过34.01%