题目
判断能否在字符网格中沿上下左右相邻格拼出 word。同一个格子在同一条路径中最多使用一次。
示例输入
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"示例输出
true思路
从每个格子尝试 DFS。字符匹配后暂时标记格子已用,再搜索下一字符;返回前恢复格子。这样其他搜索路径仍能使用它。
每一步都成立
被标记的格子恰好是当前搜索路径,恢复后 board 与调用前一致。
看它一步步执行
用的是题目示例按平常的写法填:数组写 2 7 11 15 或 2, 7, 11, 15,矩阵每行一行,字符串不用加引号。也可以把力扣的示例整行粘贴进来,例如 nums = [2,7,11,15], target = 9。
核对结果(可选)
数组 / nums步骤 1
执行状态
这次的结果
播放到最后查看Solution.java参考解法 · 高亮的是正在执行的行
1class Solution {2 public boolean exist(char[][] board, String word) {3 for (int r = 0; r < board.length; r++) {4 for (int c = 0; c < board[0].length; c++) {5 if (search(board, word, r, c, 0)) return true;6 }7 }8 return false;9 }10 private boolean search(char[][] board, String word, int r, int c, int index) {11 if (r < 0 || c < 0 || r >= board.length || c >= board[0].length12 || board[r][c] != word.charAt(index)) return false;13 if (index == word.length() - 1) return true;14 char saved = board[r][c];15 board[r][c] = '