079 Word Search 单词搜索
给定一个二维面板和一个单词,找出该单词是否存在于网格中。
这个词可由顺序相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,
给定 二维面板 =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
单词= "ABCCED",-> 返回 true,
单词 = "SEE", -> 返回 true,
单词 = "ABCB", -> 返回 false。
详见:https://leetcode.com/problems/word-search/description/
Java实现:
class Solution { public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; boolean[][] visited = new boolean[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (dfs(board, word, 0, i, j, visited)) { return true; } } } return false; } public boolean dfs(char[][] board, String word, int index, int rowindex, int colindex, boolean[][] visited) { if (index == word.length()){ return true; } if (rowindex < 0 || colindex < 0 || rowindex >=board.length || colindex >= board[0].length){ return false; } if (visited[rowindex][colindex]){ return false; } if (board[rowindex][colindex] != word.charAt(index)){ return false; } visited[rowindex][colindex] = true; boolean res = dfs(board, word, index + 1, rowindex - 1, colindex, visited) || dfs(board, word, index + 1, rowindex + 1, colindex, visited) || dfs(board, word, index + 1, rowindex, colindex + 1, visited) || dfs(board, word, index + 1, rowindex, colindex - 1, visited); visited[rowindex][colindex] = false; return res; } }
参考:https://www.cnblogs.com/springfor/p/3883942.html