Word Search, 在矩阵中寻找字符串,回溯算法
2016-08-22 19:12
232 查看
问题描述:
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 =
word =
word =
算法分析:回溯算法问题。遍历字母表矩阵,然后判断每个字母的上下左右方向是否匹配。维护一个visited数组,来记录路径上已经访问过的元素,防止重复访问。
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.
算法分析:回溯算法问题。遍历字母表矩阵,然后判断每个字母的上下左右方向是否匹配。维护一个visited数组,来记录路径上已经访问过的元素,防止重复访问。
public class WordSearch { private int row; private int col; public boolean exist(char[][] board, String word) { row = board.length; col = board[0].length; boolean[][] visited = new boolean[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (dfs(board, word, 0, i, j, visited)) return true; } } return false; } private boolean dfs(char[][] board, String word, int index, int rowindex, int colindex, boolean[][] visited) { if (index == word.length())//word全部匹配,直接返回true return true; if (rowindex < 0 || colindex < 0 || rowindex >= row || colindex >= col) return false; if (visited[rowindex][colindex])//路径上一步访问过,就忽略 return false; if (board[rowindex][colindex] != word.charAt(index))//不匹配,直接返回false return false; visited[rowindex][colindex] = true;//匹配,置visited为true //当前元素的上下左右是否匹配,只要有一个方向匹配,返回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;//递归完后将visited重置为false return res; } }
相关文章推荐
- 算法笔记学习000——Smith-Waterman算法寻找两个字符串中匹配度最高的子串
- 字符串中寻找汉字
- 已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde 的个数,如果没有返回0,有的话返回子字符串的个数。
- 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bccced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中
- 动态规划——寻找子矩阵最大和
- 寻找兄弟字符串
- 寻找若干个字符串的最长公共前缀 Longest Common Prefix
- C++初学初练数学指针与字符串之矩阵初练
- 寻找输入的回文字符串并输出!!
- BZOJ_4002_[JLOI2015]有意义的字符串_矩阵乘法
- 寻找字符串中出现次数最多的字符
- 两个字符串寻找最长公共子串
- [字符串与矩阵乘法]
- 寻找若干个字符串的最长公共前缀
- word search 此题若会,所有dfs矩阵全会
- 【bzoj4002】[JLOI2015]有意义的字符串 数论+矩阵乘法
- 已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,如果没有返回0,有的话返回子字符串的个数
- 寻找一个字符串中连续出现次数最多的子串
- 寻找一个字符串中连续出现次数最多的子串
- 关于数组指针,指针数组,双重数组,二维矩阵,字符串数组,双重字符指针的理解