【LeetCode】Word Search 解题报告
2015-05-19 16:39
120 查看
【题目】
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
word =
-> returns
word =
-> returns
word =
-> returns
【解析】
二维数组的字符矩阵,给定一个字符串word,问能不能在字符矩阵中找到这个word,字符矩阵中的字符可以上下左右四个方向形成字符串。
直接用DFS回溯就好。
【Java代码】
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word =
"ABCCED",
-> returns
true,
word =
"SEE",
-> returns
true,
word =
"ABCB",
-> returns
false.
【解析】
二维数组的字符矩阵,给定一个字符串word,问能不能在字符矩阵中找到这个word,字符矩阵中的字符可以上下左右四个方向形成字符串。
直接用DFS回溯就好。
【Java代码】
public class Solution { public boolean exist(char[][] board, String word) { int m = board.length; int n = board[0].length; boolean[][] visited = new boolean[m] ; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (dfs(board, visited, i, j, word, 0)) return true; } } return false; } public boolean dfs(char[][] board, boolean[][] visited, int x, int y, String word, int k) { if (k == word.length()) return true; if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return false; if (visited[x][y]) return false; if (board[x][y] != word.charAt(k)) return false; visited[x][y] = true; if (dfs(board, visited, x - 1, y, word, k + 1)) return true; if (dfs(board, visited, x + 1, y, word, k + 1)) return true; if (dfs(board, visited, x, y - 1, word, k + 1)) return true; if (dfs(board, visited, x, y + 1, word, k + 1)) return true; visited[x][y] = false; return false; } }
相关文章推荐
- [leetcode] 79. Word Search 解题报告
- LeetCode: Word Search 解题报告
- [LeetCode] Word Search 解题报告
- [LeetCode] Word Search 解题报告
- 【LeetCode】Word Search 解题报告
- 【LeetCode】79. Word Search 解题报告(Python)
- [Leetcode] 79. Word Search 解题报告
- [Leetcode] 656. Coin Path 解题报告
- [LeetCode] 415. Add Strings 解题报告
- [Leetcode] 664. Strange Printer 解题报告
- [Leetcode] 669. Trim a Binary Search Tree 解题报告
- leetCode 79.Word Search (词搜索) 解题思路和方法
- LeetCode-Single Number-解题报告
- [Leetcode] 124. Binary Tree Maximum Path Sum 解题报告
- [LeetCode] 417. Pacific Atlantic Water Flow 解题报告
- [Leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告
- [LeetCode]Same Tree解题报告
- LeetCode: Multiply Strings 解题报告
- [Leetcode] 133. Clone Graph 解题报告
- [Leetcode] 776. Split BST 解题报告