Leetcode题目79.单词搜索(回溯+DFS-中等)
题目描述:
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true. 给定 word = "SEE", 返回 true. 给定 word = "ABCB", 返回 false.
代码实现:
class Solution { public static boolean exist(char[][] board, String word) { if (board.length == 0) { return false; } //网格的行数 int row = board.length; //网格的列数 int col = board[0].length; //表示网格是否已经被访问过的状态 boolean[][] visited = new boolean[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (board[i][j] == word.charAt(0) && backTrace(i, j, 0, board, word, visited)) { return true; } } } return false; } //DFS+回溯 private static boolean backTrace(int i, int j, int index, char[][] board, String word, boolean[][] visited) { if (index == word.length()) { return true; } //二维平面按照上->右->下->左的顺序搜索 if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(index) || visited[i][j]) { return false; } //标记当前网格已经被访问 visited[i][j] = true; if (backTrace(i - 1, j, index + 1, board, word, visited) || backTrace(i, j + 1, index + 1, board, word, visited) || backTrace(i + 1, j, index + 1, board, word, visited) || backTrace(i, j - 1, index + 1, board, word, visited)) { return true; } //回溯 visited[i][j] = false; return false; } }