题目
给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
和word
仅由大小写英文字母组成
解答
源代码
class Solution {public boolean exist(char[][] board, String word) {// 表示当前格子是否被经过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 (dfs(board, i, j, word, 0, visited)) {return true;}}}return false;}public boolean dfs(char[][] board, int i, int j, String word, int k, boolean visited[][]) {// 当前格子和word的k索引对应的字符不一致if (board[i][j] != word.charAt(k)) {return false;}// 已经到word单词的最后一个字符if (k == word.length() - 1) {return true;}visited[i][j] = true;int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};for (int[] dir : dirs) {int x = dir[0], y = dir[1];int newi = i + x, newj = j + y;if (newi >= 0 && newj >= 0 && newi <board.length && newj < board[0].length && visited[newi][newj] == false) {if (dfs(board, newi, newj, word, k + 1, visited)) {return true;} else {continue;}}}visited[i][j] = false;return false;}
}
总结
这个题目还挺熟悉的,应该是大一小学期实训的时候做过,那时候做的是迷宫问题,都是方向+回溯。