LeetCode--Word Search
2017-10-13 15:51
351 查看
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.
思路:深度优先搜索。首先二层循环找到第一个字母,然后递归调用,深度搜索,从上下左右四个方向依次找下一个字母,如果失败则回溯到上一层,注意同一层找到搜索过的字母不重复搜索。
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.
思路:深度优先搜索。首先二层循环找到第一个字母,然后递归调用,深度搜索,从上下左右四个方向依次找下一个字母,如果失败则回溯到上一层,注意同一层找到搜索过的字母不重复搜索。
class Solution { public: bool exist(vector<vector<char>>& board, string word) { int m=board.size(),n=board[0].size(); vector<vector<bool>>visited(m,vector<bool>(n,false)); 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; } bool dfs(vector<vector<char>>board,string word,int index,int x,int y,vector<vector<bool>>&visited){ if(index==word.size()) return true; if(x<0||y<0||x>=board.size()||y>board[0].size()) return false; if(visited[x][y]) return false; if(board[x][y]!=word[index]) return false; visited[x][y]=true; bool ret=dfs(board,word,index+1,x-1,y,visited)|| dfs(board,word,index+1,x+1,y,visited)|| dfs(board,word,index+1,x,y-1,visited)|| dfs(board,word,index+1,x,y+1,visited); visited[x][y]=false; return ret; } };
相关文章推荐
- Leetcode-79_Word Searchr-典型深搜题-【C++】
- [leetCode]79(Word Search)
- [leetcode ] word search
- [leetcode] 79.Word Search
- leetcode word search
- [leetcode]Word Search
- Word Search - Leetcode
- 【LeetCode-面试算法经典-Java实现】【079-Word Search(单词搜索)】
- [LeetCode] Word Search
- Leetcode:Word Search
- Leetcode 79. Word Search
- leetcode:Word Search
- LeetCode:Word Search
- 【leetcode】Word Search
- LeetCode: Word Search
- LeetCode(78) Word Search
- leetCode 79. Word Search
- LeetCode题解 #79 Word Search
- [LeetCode][JavaScript]Word Search
- leetcode-word search