题目
给定一个 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: vector<vector<int>> dirs={{1,0},{-1,0},{0,1},{0,-1}}; vector<vector<bool>> visit; bool dfs(vector<vector<char>>& board,string& word,int index,int x,int y){ if(index==word.size()) return true; if(x<0||x>=board.size()||y<0||y>=board[0].size()) return false; if(visit[x][y]) return false; char c=word[index]; if(board[x][y]!=c) return false; for(vector<int>& dir:dirs){ int nx=x+dir[0]; int ny=y+dir[1]; visit[x][y]=true; if(dfs(board,word,index+1,nx,ny)) return true; visit[x][y]=false; } return false; } bool exist(vector<vector<char>>& board, string word) { for(int i=0;i<board.size();i++){ for(int j=0;j<board[0].size();j++){ visit=vector<vector<bool>>(board.size(),vector<bool>(board[0].size(),false)); if(dfs(board,word,0,i,j)) return true; } } return false; } };