力扣-79-搜索单词

题目:传送门

用深度优先搜索就行了,注意只能上下左右四个方向,注意不能越出界限,走过的地方不能重复走。代码的条件有点多,注意细节。

#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

typedef vector<int> vec;
typedef vector<vec> mat;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};


class Solution {
public:
    bool dfs(string& word, vector<vector<char>>& board, mat& flag,int x, int y, int cnt, int index){
        if(cnt == 0){
            return true;        
        }
        for(int i = index; i < word.length(); i++)
        {
            for(int k = 0; k < 4; k++)
            {
                int nx = x + dx[k], ny = y + dy[k];
                if(nx < 0 || nx >= board.size()|| ny < 0 || ny >= board[0].size()) continue;
                if (word[i] == board[nx][ny]&& flag[nx][ny]==0)
                {
                    flag[nx][ny] = 1;
                    if(dfs(word, board, flag, nx, ny, cnt-1, i+1)) return true;
                    flag[nx][ny] = 0;
                }
            }
            return false;
        } 
        return false;//若未返回true,主函数调用处返回false
    }
    bool exist(vector<vector<char>>& board, string word) {
        int num = word.size();
        mat flag(board.size(), vec(board[0].size()));
        for (int i = 0; i < board.size(); i++)
            for(int j = 0; j < board[0].size(); j++){
                if(board[i][j] != word[0]) continue;
                flag[i][j] = 1;
                if(dfs(word, board, flag, i, j, num-1, 1)) return true;
                flag[i][j] = 0;
            }
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/xiazhenbin/p/13380880.html