【leetcode题解】2 - Word Search

来源:互联网 发布:Green VPN网络加速器 编辑:程序博客网 时间:2024/04/28 17:41

Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

leetcode题目链接


解题思路:

* BFS + DFS

* 每次找一个字符,使用BFS

* 第一个字符的位置遍历整个board得到

* 从第i个找第i+1个只能查找周围没有被使用过的,用DFS

* 用数组标记每个位置是否已被使用


源码:

class Solution {public:    void DFS(vector<vector<char> > &board, vector<vector<bool> > &vvused, string &word, int deep, int x, int y)    {        if (bfound || (board[x][y] != word[deep]))            return;        if (deep == (word.size() - 1))  // 找到最后一个字符        {            bfound = true;            return;        }                vvused[x][y] = true;  // used        if ((x > 0) && !vvused[x-1][y])            DFS(board, vvused, word, deep+1, x-1, y);  // up        if ((x < n-1) && !vvused[x+1][y])            DFS(board, vvused, word, deep+1, x+1, y);  // down        if ((y > 0) && !vvused[x][y-1])            DFS(board, vvused, word, deep+1, x, y-1);  // left        if ((y < m-1) && !vvused[x][y+1])            DFS(board, vvused, word, deep+1, x, y+1);  // right                vvused[x][y] = false; // 回退之前还原标志位        return;    }    bool exist(vector<vector<char> > &board, string word) {                // BFS + DFS        // 每次找一个字符,使用BFS        // 从第i个找第i+1个只能查找周围没有被使用过的,用DFS        // 用数组标记每个位置是否已被使用        if (board.size() == 0)            return false;                n = board.size();        m = board[0].size();        bfound = false;        vector<vector<bool> > vvused(board.size(), vector<bool>(board[0].size(), false));                for (int i = 0; i < n; ++i)            for (int j = 0; j < m; ++j)                DFS(board, vvused, word, 0, i, j);        return bfound;    }private:    bool bfound;    int n;    int m;};


0 0