// 执行用时: 44 ms // 内存消耗: 11.1 MB classSolution { public: vector<vector<char>> b; vector<vector<bool>> st; int m, n; string w; int len; constint dr[4] = {-1, 0, 1, 0}, dc[4] = {0, 1, 0, -1}; boolexist(vector<vector<char>>& board, stringword){ b = board, w = word; m = b.size(), n = b[0].size(); len = word.size(); st = vector<vector<bool>> (m, vector<bool>(n, false));
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (b[i][j] == w[0]) { if (dfs(i, j, 0)) returntrue; } } }
returnfalse; }
booldfs(int r, int c, int u){ if (b[r][c] != w[u]) { returnfalse; } if (u == len - 1) { returntrue; } // 正确的节点 st[r][c] = true;
for (int d = 0; d < 4; d++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && !st[ner][nec]) { if (dfs(ner, nec, u + 1)) returntrue; } } // 恢复现场 st[r][c] = false; returnfalse; } };
// 执行用时: 7 ms // 内存消耗: 40.1 MB classSolution{ char[][] b; String w; int m, n; int len; int[] dr, dc; boolean[][] st; publicbooleanexist(char[][] board, String word){ b = board; w = word; m = b.length; n = b[0].length; len = w.length(); dr = newint[] {-1, 0, 1, 0}; dc = newint[] {0, 1, 0, -1}; st = newboolean[m][n]; for (int i = 0; i < m; i++) { Arrays.fill(st[i], false); }
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (b[i][j] == w.charAt(0)) { if (dfs(i, j, 0)) returntrue; } } }
returnfalse; }
privatebooleandfs(int r, int c, int u){ if (b[r][c] != w.charAt(u)) returnfalse; if (u == len - 1) returntrue; // else keep checking st[r][c] = true;
for (int d = 0; d < 4; d ++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && !st[ner][nec]) { if (dfs(ner, nec, u + 1)) returntrue; } } st[r][c] = false; returnfalse; } }