给定一个 m x n
二维字符网格 board
和一个字符串单词 word
。如果 word
存在于网格中,返回 true
;否则,返回 false
。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" 输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" 输出:false
class Solution { public: int m,n; vector<vector<int>> direction={ {-1,0},{1,0},{0,-1},{0,1} }; bool dfs(vector<vector<char>>& board,vector<vector<int>>& isVisited,int i,int j,string word,int start){ if(start==word.size()){// 全部匹配成功 return true; } //判断是否越界以及当前字符是否与word中index下的字符相等以及当前字符未被访问 if(i<0||i>=m||j<0||j>=n||board[i][j]!=word[start]||isVisited[i][j]==1){ return false; } isVisited[i][j]=1;//标记该元素已被访问 for(int k=0;k<4;k++){//遍历四个方向 int x = i+direction[k][0]; int y = j+direction[k][1]; if(dfs(board,isVisited,x,y,word,start+1)){//找到匹配,直接返回true,不用再继续遍历 return true; } } //当前字符未找到下一个匹配的字符,回溯,标记该元素未被访问 isVisited[i][j]=0; return false; } bool exist(vector<vector<char>>& board, string word) { m = board.size();//行 n = board[0].size();//列 vector<vector<int>> isVisited(m,vector<int>(n,0));//初始化访问数组 for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ bool res = dfs(board,isVisited,i,j,word,0); if(res) return res; //一旦匹配,直接返回true } } return false; } };
标签:word,int,单元格,单词,vector,搜索,board,回溯,true From: https://www.cnblogs.com/yueshengd/p/18645372