1. 程式人生 > 其它 >【leetcode】79. Word Search

【leetcode】79. Word Search

  Given anm x ngrid of charactersboardand a stringword, returntrueifwordexists in the grid.The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
class Solution {
public:
    bool dfs(vector<vector<char>>& board,string word,int i,int j,int n){
        //遞迴終止條件
        if(n==word.size()) return true;
        if(i<0 || j<0 || i>=board.size()||j>=board[0].size() || board[i][j]!=word[n]) return false;
        board[i][j]='0'
;//這個位置檢索到了 bool flag=(dfs(board,word,i+1,j,n+1) || dfs(board,word,i-1,j,n+1)|| dfs(board,word,i,j+1,n+1)|| dfs(board,word,i,j-1,n+1)); board[i][j]=word[n]; return flag; } bool exist(vector<vector<char>>& board, string word) {
//深度優先遞歸回溯 if(word=="") return false; int m=board.size(),n=board[0].size(); for(int i=0;i<m;++i){ for(int j=0;j<n;++j){ if(dfs(board,word,i,j,0)) return true; } } return false; } };