标签:char letter grid false lis highlight sel use search
class Solution { public: vector<vector<int>>dir={{-1,0},{1,0},{0,-1},{0,1}}; bool search(vector<vector<char>>& board,int i,int j,vector<vector<bool>>&visited,string word,int index){ if(index==word.size()) return true; if(i<0||i>=board.size()||j<0||j>=board[0].size()||visited[i][j]) return false; if(board[i][j]!=word[index]) return false; visited[i][j]=true; for(int m=0;m<4;m++){ int x=i+dir[m][0]; int y=j+dir[m][1]; if(search(board,x,y,visited,word,index+1)) return true; } visited[i][j]=false; return false; } bool exist(vector<vector<char>>& board, string word) { int m=board.size(),n=board[0].size(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ vector<vector<bool>>visited(m,vector<bool>(n,false)); if(board[i][j]==word[0] && search(board,i,j,visited,word,0)) return true; } } return false; } };
别人优秀的C++代码:
class Solution { public: bool search(vector<vector<char>>&board,int i,int j,string word,int index){ if(index==word.size()) return true; if(i<0||i>=board.size()||j<0||j>=board[0].size()) return false; char c=board[i][j]; if(c==word[index]){ board[i][j]=‘#‘; if(search(board,i+1,j,word,index+1)) return true; if(search(board,i,j+1,word,index+1)) return true; if(search(board,i-1,j,word,index+1)) return true; if(search(board,i,j-1,word,index+1)) return true; board[i][j]=c; } return false; } bool exist(vector<vector<char>>& board, string word) { int m=board.size(),n=board[0].size(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(search(board,i,j,word,0)) return true; } } return false; } };
同样都是回溯法,但是这个就没有使用visited来记录是否被访问,而且别人代码的可读性比我的要高出很多。
Python:
class Solution(object): def search(self,board,i,j,word): if len(word)==0: return True if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or board[i][j]!=word[0]: return False tmp=board[i][j] board[i][j]="#" res=(self.search(board,i+1,j,word[1:]) or self.search(board,i,j+1,word[1:]) or self.search(board,i-1,j,word[1:]) or self.search(board,i,j-1,word[1:])) board[i][j]=tmp return res def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if board is None: return False m,n=len(board),len(board[0]) for i in xrange(m): for j in xrange(n): if self.search(board,i,j,word): return True return False
标签:char letter grid false lis highlight sel use search
原文地址:https://www.cnblogs.com/xiaobaituyun/p/10645038.html