自己的思路对的,一直过不了large是因为把visit的建立放在循环最里层,导致每次都建一个两维vector耗了大量的时间。太傻逼了。。
1 class Solution { 2 public: 3 bool dfs(string word, int dep, int maxdep, vector<vector<char>> &board, int x, int y, vector<vector<bool>> &visit, int dir[4][2]) { 4 if (dep == maxdep) return true; 5 int m = board.size(); 6 int n = board[0].size(); 7 for (int i = 0; i < 4; i++) { 8 int xx = x + dir[i][0]; 9 int yy = y + dir[i][1]; 10 if (xx >= 0 && xx < m && yy >= 0 && yy < n && board[xx][yy] == word[dep] && !visit[xx][yy]) { 11 visit[xx][yy] = true; 12 if (dfs(word, dep+1, maxdep, board, xx, yy, visit, dir)) return true; 13 visit[xx][yy] = false; 14 } 15 } 16 } 17 bool exist(vector<vector<char> > &board, string word) { 18 // Start typing your C/C++ solution below 19 // DO NOT write int main() function 20 int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 21 int m = board.size(); 22 if (!m) return false; 23 int n = board[0].size(); 24 if (!word.size()) return true; 25 vector<vector<bool>> visit(m, vector<bool>(n, false)); 26 for (int i = 0; i < m; i++) { 27 for (int j = 0; j < n; j++) { 28 if (word[0] == board[i][j]) { 29 visit[i][j] = true; 30 bool flag = false; 31 if (dfs(word, 1, word.size(), board, i, j, visit, dir)) return true; 32 visit[i][j] = false; 33 } 34 } 35 } 36 return false; 37 } 38 };
C#
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public bool Exist(char[,] board, string word) { 3 int[,] dir = new int[4, 2]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 4 int m = board.GetLength(0); 5 int n = board.GetLength(1); 6 if (m == 0 || n == 0) return false; 7 bool[,] visit = new bool[m, n]; 8 for (int i = 0; i < m; i++) { 9 for (int j = 0; j < n; j++) { 10 if (word[0] == board[i, j]) { 11 visit[i, j] = true; 12 bool flag = false; 13 if (dfs(word, 1, word.Length, board, i, j, visit, dir)) return true; 14 visit[i, j] = false; 15 } 16 } 17 } 18 return false; 19 } 20 public bool dfs(string word, int dep, int maxdep, char[,] board, int x, int y, bool[,] visit, int[,] dir) { 21 if (dep == maxdep) return true; 22 int m = board.GetLength(0); 23 int n = board.GetLength(1); 24 for (int i = 0; i < 4; i++) { 25 int xx = x + dir[i, 0]; 26 int yy = y + dir[i, 1]; 27 if (xx >= 0 && xx < m && yy >= 0 && yy < n && board[xx, yy] == word[dep] && !visit[xx, yy]) { 28 visit[xx, yy] = true; 29 if (dfs(word, dep+1, maxdep, board, xx, yy, visit, dir)) return true; 30 visit[xx, yy] = false; 31 } 32 } 33 return false; 34 } 35 }