DFS with in-place marking
Time O(m · n · 3ᴸ) for word length L Space O(L)dfs(r, c, i): fail if out of bounds or board[r][c] != word[i]. If i is the last index, succeed. Otherwise mark, try four directions with i + 1, restore.
class Solution {
public boolean exist(char[][] board, String word) {
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board[0].length; c++)
if (dfs(board, word, r, c, 0)) return true;
return false;
}
private boolean dfs(char[][] b, String w, int r, int c, int i) {
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != w.charAt(i)) return false;
if (i == w.length() - 1) return true;
char saved = b[r][c];
b[r][c] = '#'; // mark as used
boolean found = dfs(b, w, r + 1, c, i + 1) || dfs(b, w, r - 1, c, i + 1)
|| dfs(b, w, r, c + 1, i + 1) || dfs(b, w, r, c - 1, i + 1);
b[r][c] = saved; // restore
return found;
}
}Verdict: Each step has at most 3 new directions (not back where it came from).