Leetcode 79 单词搜索 word-search tag 数组 dfs
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true. 给定 word = "SEE", 返回 true. 给定 word = "ABCB", 返回 false.
思路:
首先找到word中第一个字母所在位置,然后dfs,在每次遍历中,查找i,j四个方向中的字母,同时记录已经遍历过的位置,防止重复。直到begin==word.size()。表明已经查找完全。
class Solution { public: bool exist(vector<vector<char>>& board, string word) { int m=board.size(); int n=board[0].size(); bool res = false; for(int i=0;i<m;++i) { for(int j=0;j<n;++j) { if(word[0]==board[i][j]) { vector<vector<bool>> use(m,vector<bool>(n,false)); use[i][j]=true; res|=dfs(board,word,i,j,1,use); } } } return res; } bool dfs(vector<vector<char>>& board, string word, int i, int j, int begin, vector<vector<bool>> & use) { if(begin==word.size()) return true; bool res = false; if(i-1>=0&&board[i-1][j]==word[begin]&&!use[i-1][j]) { use[i-1][j]=true; res|=dfs(board,word,i-1,j,begin+1,use); use[i-1][j]=false; } if(i+1<board.size()&&board[i+1][j]==word[begin]&&!use[i+1][j]) { use[i+1][j]=true; res|=dfs(board,word,i+1,j,begin+1,use); use[i+1][j]=false; } if(j-1>=0&&board[i][j-1]==word[begin]&&!use[i][j-1]){ use[i][j-1]=true; res|=dfs(board,word,i,j-1,begin+1,use); use[i][j-1]=false; } if(j+1<board[0].size()&&board[i][j+1]==word[begin]&&!use[i][j+1]){ use[i][j+1]=true; res|=dfs(board,word,i,j+1,begin+1,use); use[i][j+1]=false; } return res; } };
优化的一点是,可以不创建use,而直接修改board来时间路径记录
class Solution { public: bool exist(vector<vector<char>>& board, string word) { int m=board.size(); int n=board[0].size(); bool res = false; for(int i=0;i<m;++i) { for(int j=0;j<n;++j) { if(word[0]==board[i][j]) { board[i][j]='!'; res|=dfs(board,word,i,j,1); board[i][j]=word[0]; } } } return res; } bool dfs(vector<vector<char>>& board, string word, int i, int j, int begin) { if(begin==word.size()) return true; bool res = false; if(i-1>=0&&board[i-1][j]==word[begin]) { board[i-1][j]='!'; res|=dfs(board,word,i-1,j,begin+1); board[i-1][j]=word[begin]; } if(i+1<board.size()&&board[i+1][j]==word[begin]) { board[i+1][j]='!'; res|=dfs(board,word,i+1,j,begin+1); board[i+1][j]=word[begin]; } if(j-1>=0&&board[i][j-1]==word[begin]){ board[i][j-1]='!'; res|=dfs(board,word,i,j-1,begin+1); board[i][j-1]=word[begin]; } if(j+1<board[0].size()&&board[i][j+1]==word[begin]){ board[i][j+1]='!'; res|=dfs(board,word,i,j+1,begin+1); board[i][j+1]=word[begin]; } return res; } };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=