终于搞定了这个DFS,最近这个DFS写的很不顺手,我一直以为递归这种东西只是在解重构时比较麻烦,现在看来,连最简单的返回true和false的逻辑关系都不能说one hundred present 搞定。
人品啊TLE:
1 class Solution { 2 public: 3 bool legal(int i, int j, vector<vector<char>> board) 4 { 5 if (i >= 0 && i < board.size() && j >= 0 && j < board[i].size()) 6 return true; 7 return false; 8 } 9 10 bool dfs(vector<vector<char>>& board, string word, int t, int i, int j, vector<vector<bool>> visited) 11 { 12 if (t == word.length()) 13 return true; 14 if (board[i][j] == word[t]) 15 { 16 visited[i][j] = true; 17 if (legal(i - 1, j, board) && !visited[i - 1][j] && dfs(board, word, t + 1, i - 1, j, visited)) 18 return true; 19 if (legal(i, j + 1, board) && !visited[i][j + 1] && dfs(board, word, t + 1, i, j + 1, visited)) 20 return true; 21 if (legal(i + 1, j, board) && !visited[i + 1][j] && dfs(board, word, t + 1, i + 1, j, visited)) 22 return true; 23 if (legal(i, j - 1, board) && !visited[i][j - 1] && dfs(board, word, t + 1, i, j - 1, visited)) 24 return true; 25 } 26 visited[i][j] = false; 27 return false; 28 } 29 30 bool exist(vector<vector<char>>& board, string word) 31 { 32 int m = board.size(); 33 int n = board[0].size(); 34 vector<vector<bool>> visited(m, vector<bool>(n, false)); 35 for (int i = 0; i < board.size(); i++) 36 { 37 for (int j = 0; j < board[0].size(); j++) 38 { 39 if (dfs(board, word, 0, i, j, visited)) 40 return true; 41 } 42 } 43 return false; 44 } 45 };
为什么?
时间: 2024-11-06 18:30:09