for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (board[i][j] == word[0]) { dfs(board, word, i, j, 0); if (res) returntrue; } } } returnfalse; }
voiddfs(vector<vector<char>> &board, string &word, int r, int c, int k){ if (k == len - 1) { if (board[r][c] == word[k]) { res = true; } return; } // else if k < len - 1 if (board[r][c] != word[k]) { return; } else { // match for the current node char tmp = board[r][c]; board[r][c] = '*'; for (int i = 0; i < 4; i++) { int ner = r + dr[i], nec = c + dc[i]; if (ner < 0 || ner > R - 1 || nec < 0 || nec > C - 1 || board[ner][nec] == '*') continue; dfs(board, word, ner, nec, k + 1); if (res) return; // if found, return } // not match for the next 4 directions // restore board[r][c] = tmp; } } };
// 执行用时: 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; } }