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.
Have you been asked this question in an interview?
无他,DFS耳。
- int depth;
- bool dfs(vector<vector<char>> &board, string word,int i,int j,vector<vector<bool>> &m){
- depth++;
- int len=word.length();
- if(i<0 || i>=board.size() || j<0 || j>=board[0].size()){
- depth--;
- return false;
- }
- if((depth==len) && (board[i][j]==word[depth-1])){
- depth--;
- return true;
- }
- if(depth>word.length()){
- depth--;
- return false;
- }
- if(board[i][j]!=word[depth-1]){
- depth--;
- return false;
- }
- if(i-1>=0 && i-1<board.size() && j>=0 && j<board[0].size() ){
- if(m[i-1][j]==false ){
- m[i-1][j]=true;
- if(dfs(board,word,i-1,j,m)==true){
- depth--;
- return true;
- }
- m[i-1][j]=false;
- }
- }
- if(i+1>=0 && i+1<board.size() && j>=0 && j<board[0].size()){
- if(m[i+1][j]==false){
- m[i+1][j]=true;
- if(dfs(board,word,i+1,j,m)==true){
- depth--;
- return true;
- }
- m[i+1][j]=false;
- }
- }
- if(i>=0 && i<board.size() && j-1>=0 && j-1<board[0].size()){
- if(m[i][j-1]==false){
- m[i][j-1]=true;
- if(dfs(board,word,i,j-1,m)==true){
- depth--;
- return true;
- }
- m[i][j-1]=false;
- }
- }
- if(i>=0 && i<board.size() && j+1>=0 && j+1<board[0].size()){
- if(m[i][j+1]==false){
- m[i][j+1]=true;
- if(dfs(board,word,i,j+1,m)==true){
- depth--;
- return true;
- }
- m[i][j+1]=false;
- }
- }
- depth--;
- return false;
- }
- bool exist(vector<vector<char> > &board, string word) {
- vector<vector<bool>> m(board.size(),vector<bool>(board[0].size(),false));
- for(int i=0;i<board.size();i++){
- for(int j=0;j<board[0].size();j++){
- if(board[i][j]==word[0]){
- m[i][j]=true;
- if(dfs(board,word,i,j,m))
- return true;
- m[i][j]=false;
- }
- }
- }
- return false;
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(3) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文介绍了如何在二维网格中搜索指定单词,采用深度优先搜索(DFS)算法,确保单词由相邻单元格构成且不重复使用同一字母单元格。
327

被折叠的 条评论
为什么被折叠?



