Word Search
来源:互联网 发布:淘宝联盟禁止微信 编辑:程序博客网 时间:2024/05/22 11:45
Word Search
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
.Solution:
1. Keep a two-dimensional matrix to store the state representing whether the cell has been visited or not.
2. Use DFS to traverse the whole board one by one.
3. Pay attention to the base case of the recursion method.
4. Backtracking. restore the visit matrix every time reaching the end of the DFS method.
public class Solution { public boolean exist(char[][] board, String word) { if (board == null || board.length == 0) return false; int row = board.length; int col = board[0].length; boolean[][] visit = new boolean[row][col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { if (dfs(board, word, i, j, 0, visit)) return true; } return false; } public boolean dfs(char[][] board, String word, int i, int j, int wordIndex, boolean[][] visit) { int row = board.length; int col = board[0].length; if (wordIndex >= word.length()) return true; if (i < 0 || i >= row || j < 0 || j >= col) return false; if (word.charAt(wordIndex) != board[i][j]) return false; if (visit[i][j] == true) return false; visit[i][j] = true; if (dfs(board, word, i - 1, j, wordIndex + 1, visit)) return true; if (dfs(board, word, i + 1, j, wordIndex + 1, visit)) return true; if (dfs(board, word, i, j - 1, wordIndex + 1, visit)) return true; if (dfs(board, word, i, j + 1, wordIndex + 1, visit)) return true; visit[i][j] = false; return false; }}
0 0
- Word Search
- Word Search
- word search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Spring MVC 拦截器
- CentOS搭建SVN服务器
- hdu 1157
- [leetcode] Best Time to Buy and Sell Stock II
- POJ2528 Mayor's poster 线段树 插入 查询 删除
- Word Search
- 深度优先搜索和广度优先搜索的比较与分析
- 用迭代法求 x=根号a。求平方根的迭代公式为:X(n+1)=(Xn+a/Xn) /2。
- XMemcachedClient实例的add方法和set方法区别
- 寻找最小生成树的kruskal算法的java实现
- Android数据库SQLite使用详解三 : 数据库的升级
- 形参默认参数
- 吹毛求疵-命名空间要解决的问题
- Memcached Java Client API详解