单词搜索

给出一个二维的字母板和一个单词,寻找字母板网格中是否存在这个单词。

单词可以由按顺序的相邻单元的字母组成,其中相邻单元指的是水平或者垂直方向相邻。每个单元中的字母最多只能使用一次。

样例

给出board =

[

  "ABCE",

  "SFCS",

  "ADEE"

]

word = "ABCCED", ->返回 true,

word = "SEE",-> 返回 true,

word = "ABCB", -> 返回 false

class Solution {
public:
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    bool exist(vector<vector<char> > &board, string word) {
        // write your code here
        int m = board.size();
        int n = board[0].size();

        vector<vector<bool> > flag;
        for (int i = 0; i < m; i++)
        {
            vector<bool> temp;
            for (int j = 0; j < n; j++)
            {
                temp.push_back(false);
            }
            flag.push_back(temp);
        }
        bool found = false;
        int k = word.length();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                visit(board, m, n, i, j, word, k, 0, flag, found);
                if (found)
                {
                    return true;
                }
            }
        }

        return false;
    }
private:
    void visit(vector<vector<char> > &board, int m, int n, 
           int row, int column, string &word, int k, int pos, 
           vector<vector<bool> > &flag, bool &found)
    {
        if (found)
        {
            return;
        }
        if (row < 0 || row >= m || column < 0 || column >= n)
        {
            return;
        }
        if (flag[row][column])
        {
            return;
        }
        int nextPos = pos;
        if (board[row][column] == word[pos])
        {
            if (pos == k-1)
            {
                found = true;
                return;
            }
            flag[row][column] = true;
            nextPos = pos+1;
        }
        else
        {
            return;
        }

        visit(board, m, n, row-1, column, word, k, nextPos, flag, found);
        visit(board, m, n, row+1, column, word, k, nextPos, flag, found);
        visit(board, m, n, row, column-1, word, k, nextPos, flag, found);
        visit(board, m, n, row, column+1, word, k, nextPos, flag, found);

        flag[row][column] = false;
    }
};

.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值