首页 > 代码库 > LeetCode Word Search
LeetCode 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
.
class Solution { public: bool dfs(int depth,vector<vector<char> >&board,string word,int x,int y){ if(depth==word.size()) { return true; } else if(x>=board.size()||x<0)return false; else if(y>=board[0].size()||y<0)return false; else { if(board[x][y]==word[depth]) { board[x][y]='.'; if(dfs(depth+1,board,word,x+1,y))return true; if(dfs(depth+1,board,word,x,y+1))return true; if(dfs(depth+1,board,word,x-1,y))return true; if(dfs(depth+1,board,word,x,y-1))return true; board[x][y]=word[depth]; return false; } else return false; } } bool exist(vector<vector<char> > &board, string word) { bool f=false; if(board.size()==0)return false; if(board[0].size()==0)return true; for(int i=0;i<board.size();++i) for(int j=0;j<board[0].size();++j) { if(dfs(0,board,word,i,j)) f=true; } //if(f==true)cout<<"true"<<endl; //else std::cout << "false" << std::endl; return f; } };
LeetCode Word Search
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。