79.|79. Word Search

【79.|79. Word Search】Medium
简直是教科书般的DFS+Backtracking. 几个地方可能会出错:

  • 如何开始搜索, 这里是看第一个单词符合就开始搜索,如果返回true就说明找到了一个,找到了就返回true
  • 找到一个,要么就是或 || 找到了返回true, 要么就是for循环一个一个试(permutation),这里是或.这里的backtracking其实就是visited[i][j]最后变回false;
class Solution { public boolean exist(char[][] board, String word) { if (board == null || board.length == 0 || board[0].length == 0){ return false; } boolean[][] visited = new boolean[board.length][board[0].length]; for (int i = 0; i < board.length; i++){ for (int j = 0; j < board[0].length; j++){ if (board[i][j] == word.charAt(0) && dfsHelper(board, i, j, word, 0, visited)){ return true; } } } return false; }private boolean dfsHelper(char[][] board, int i, int j, String word, int charIndex, boolean[][] visited){ if (charIndex == word.length()){ return true; } if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || word.charAt(charIndex) != board[i][j]){ return false; } visited[i][j] = true; if (dfsHelper(board, i + 1, j, word, charIndex + 1, visited) || dfsHelper(board, i - 1, j, word, charIndex + 1, visited)|| dfsHelper(board, i, j + 1, word, charIndex + 1, visited) || dfsHelper(board, i, j - 1, word, charIndex + 1, visited)){ return true; } visited[i][j] = false; return false; } }

    推荐阅读