標籤:
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.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
解題思路:
使用深度優先搜尋的方法,從二維數組中的每個點出發,向上下左右進行延伸,根據判定條件及時判斷;
解題步驟:
1、寫一個主函數:
(1)獲得二維數組的行列大小;
(2)遍曆所有二維數組元素,對每個元素作為搜尋起點,調用遞迴函式;
2、寫一個遞迴函式,參數為:二維數組(引用)、待匹配的字串(c字串形式方便)、當前運動到的座標值x和y、二維數組大小m和n;
(1)終止判定條件:x和y無效、當前運動到的字元不是字串下一個字元;
(2)如果已經到達匹配字串末尾,返回true
(3)暫時將當前運動到的座標字元置換為‘\0‘,因為要做出標記,以免重複折返運動;
(4)調用4個遞迴函式,分別運動到當前運動字元的上下左右四周,並判定;
(5)如果4個遞迴函式都false,則換回被置換的‘\0‘,返回false;
代碼:
1 class Solution { 2 public: 3 bool exist(vector<vector<char> > &board, string word) { 4 m = board.size(); 5 n = board[0].size(); 6 for(int x = 0; x < m; x++) { 7 for(int y = 0; y < n; y++) { 8 if(isFound(board, word.c_str(), x, y)) 9 return true;10 }11 }12 return false;13 }14 15 private:16 int m;17 int n;18 bool isFound(vector<vector<char> > &board, const char* w, int x, int y) {19 if(x < 0 || y < 0 || x >= m || y >= n || *w != board[x][y])20 return false;21 if(*(w + 1) == ‘\0‘)22 return true;23 char t = board[x][y];24 board[x][y] = ‘\0‘;25 if(isFound(board, w + 1, x - 1, y) || 26 isFound(board, w + 1, x + 1, y) || 27 isFound(board, w + 1, x, y - 1) || 28 isFound(board, w + 1, x, y + 1))29 return true; 30 board[x][y]=t;31 return false;32 }33 };
【Leetcode】【Medium】word search