個人思路:
1.首先得在board中尋找首元素可能出現的位置,對每一個合法的開始位置進行dfs
2.每次dfs的過程當中,結合backtracing避免回退優化
class Solution { public: void dfs(vector<vector<char>>& board, string curs,int row,int col,int m ,int n,bool & status) { if (status) return; if (curs.length() <= 0) { status = true; return; } if (row < 0 || row >= m || col < 0 || col >= n) { return; } char ch = board[row][col]; if (ch != curs[0]) return; string s = curs.substr(1); board[row][col] = '.'; dfs(board, s, row + 1, col, m, n, status); dfs(board, s, row - 1, col, m, n, status); dfs(board, s, row, col + 1, m, n, status); dfs(board, s, row, col - 1, m, n, status); board[row][col] = ch; } bool exist(vector<vector<char>>& board, string word) { int m = board.size(); if (m <= 0) return false; int n = board[0].size(); if (n <= 0) return false; int lens = word.length(); if (lens <= 0) return true; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { char ch = board[i][j]; if (ch == word[0]) { bool status = false; dfs(board, word, i, j, m, n, status); if (status) return true; } } } return false; } };
Leetcode - 212. Word Search IIcode
diff : 出現的是一個word集合,將知足條件的word加入到結果中ip
須要作的是對集合中的每個word均調用一次word searchci
Attention:這是一種比較死板的作法,實測Time ~ 1500ms 左右
只是在這個dfs + backtracing的專題內介紹這種模板的通用性寫法
須要注意的幾個能夠優化的細節:
1.words可能會重複,去重的過程能夠作優化
2.一個隱晦的細節(Note:You may assume that all inputs are consist of lowercase letters a-z.),這個上題中沒有說起的細節是本題優化的另外一個方向
3.在(1.設置狀態 2.dfs 3.恢復狀態)的典型回溯過程當中,若一個dfs函數獲得可行解,那麼則可跳過其餘的dfs,直接恢復狀態而後returnleetcode
class Solution { public: void dfs(vector<vector<char>>& board, string s, int row, int col, int m, int n,bool & status) { if (status) return; if (s.length() <= 0) { status = true; return; } if (row < 0 || row >= m || col < 0 || col >= n) return; char ch = board[row][col]; if (ch != s[0]) return; string str = s.substr(1); board[row][col] = '0'; dfs(board, str, row + 1, col, m, n, status); dfs(board, str, row - 1, col, m, n, status); dfs(board, str, row, col + 1, m, n, status); dfs(board, str, row, col - 1, m, n, status); board[row][col] = ch; } bool helper(vector<vector<char>>& board, string curs) { int m = board.size(); if (m <= 0) return false; int n = board[0].size(); if (n <= 0) return false; if (curs.length() <= 0) return false; char ch = curs[0]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (ch == board[i][j]) { bool status = false; dfs(board, curs, i, j, m, n, status); if (status) return true; } } } return false; } vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { vector<string> vct; int words_len = words.size(); if (words_len <= 0) return vct; sort(words.begin(), words.end()); for (int i = 0;i < words_len;++i) { if (i > 0 && words[i] == words[i - 1]) continue; if (helper(board, words[i])) vct.push_back(words[i]); } return vct; } };