LeetCode 079 Word Search
来源:互联网 发布:http请求格式 json 编辑:程序博客网 时间:2024/06/05 18:53
题目描述
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 =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED“, -> returns true,
word = “SEE“, -> returns true,
word = “ABCB“, -> returns false.
分析
典型问题,回溯法(深度优先搜索DFS),暴力破解。以每一个字符为起点,分别判断上下左右四个字符是否符合条件。符合条件则一直向下寻找,否则回退。
代码
public static boolean exist(char[][] board, String word) { if (board == null || board[0].length == 0 || board.length == 0 || word == null) { return false; } int rows = board.length; int cols = board[0].length; boolean[] visited = new boolean[rows * cols]; int pathLength = 0; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { // 以row,col为开始,能够遍历得到结果 if (dfs(board, rows, cols, row, col, word, pathLength, visited)) { return true; } } } return false; } public static boolean dfs(char[][] board, int rows, int cols, int row, int col, String word, int pathLength, boolean[] visited) { // 如果pathLength的长度已经是查找字串的长度,则已经找到 if (pathLength == word.length()) { return true; } boolean hasPath = false; // 符合条件的情况: // 1. 行、列均在矩阵范围内 // 2. board[row][col]是所要找的字符 // 3. board[row][col]没有遍历过 if (row >= 0 && row < rows && col >= 0 && col < cols && board[row][col] == word.charAt(pathLength) && !visited[row * cols + col]) { pathLength++; visited[row * cols + col] = true; hasPath = dfs(board, rows, cols, row, col - 1, word, pathLength, visited) || dfs(board, rows, cols, row - 1, col, word, pathLength, visited) || dfs(board, rows, cols, row, col + 1, word, pathLength, visited) || dfs(board, rows, cols, row + 1, col, word, pathLength, visited); // 若board[row][col]的前后左右没有满足条件的字符,则回退 if (!hasPath) { pathLength--; visited[row * cols + col] = false; } } return hasPath; }
0 0
- LeetCode: Word Search [079]
- 079 Word Search[Leetcode]
- LeetCode 079 Word Search
- leetcode 079 word search
- leetcode 079 —— Word Search
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- 关于存储过程的函数
- Ubuntu 12.04 LTS 下安装LTIB
- 【日常学习】【归并逆序对】codevs1688 求逆序对题解
- Eclipse+SVN
- Android studio 下出现"Cannot resolve symbol R"的解决方法
- LeetCode 079 Word Search
- 语音搜索,服务入口
- 【基础练习】【归并逆序对】codevs3324 新斯诺克题解
- 第19讲----项目1 字母及其编码
- ajaxFileUpload.js 修复"unexpected token '<'" bug
- matlab 有约束与无约束优化求解 optimization
- 如何自建FTP站点
- android 源代码修改了之后编译生成本地的sdk,以方便在eclipse里面直接使用,调用所改动的API接口函数
- C++调用C函数,为什么要加extern "C"?