1. 程式人生 > 實用技巧 >去除重疊區間

去除重疊區間

思路

dfs +剪枝

程式碼實現

 1 class Solution {
 2 private:
 3     int d[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
 4     int m, n;   //n行m列
 5     bool vis[210][210] = {false};
 6     
 7 public:
 8     bool exist(vector<vector<char>>& board, string word) {
 9         n = board.size();
10         m = board[0
].size(); 11 12 for(int i = 0; i < n; ++i) { 13 for(int j = 0; j < m; ++j) { 14 //memset(vis, false, sizeof(vis)); 15 //vector<vector<bool>> vis(n, vector<bool>(m, false)); //使用vector會超時,不知道為啥 16 if(dfs(board, word, i, j, 0
)) 17 return true; 18 } 19 } 20 return false; 21 } 22 23 //當前搜尋第index個字元 24 bool dfs(vector<vector<char>>& board, string targetWord, int x, int y, int index) { 25 26 //剪枝 27 if(board[x][y] != targetWord[index])
28 return false; 29 30 //剪枝 31 if(index == targetWord.length()-1) 32 return true; 33 34 vis[x][y] = true; 35 36 for(int i = 0; i < 4; ++i) { 37 int xx = x + d[i][0]; 38 int yy = y + d[i][1]; 39 if(xx < 0 || yy < 0 || xx >= n || yy >= m || vis[xx][yy]) 40 continue; 41 42 if(dfs(board, targetWord, xx, yy, index+1)) 43 return true; 44 45 } 46 47 vis[x][y] = false; //記得回溯 48 return false; 49 } 50 };

複雜度分析

參考

面試題12. 矩陣中的路徑(深度優先搜尋 DFS ,清晰圖解)