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