首页 > 代码库 > [LeetCode] Word Search [37]

[LeetCode] Word Search [37]

题目

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.

原题链接(点我)

解题思路

给一个二维字符数组,给一个字符串,问该二维数组是否包含该字符串。比如一个二维数组[ ABCE SFCS ADEE ]和字符串"ABCCED",这个就包含。解决这个问题,主要的关键是怎么解决在二维数组中查找方向,如何来标识哪些是走过的。

代码实现

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        int m = board.size();
        if(m<=0) return false;
        int n = board[0].size();
        for(int i=0; i<m; ++i)
            for(int j=0; j<n; ++j){
                if(helper(0, word, i, j, board))
                    return true;
            }
        return false;
    }
    
    bool helper(int k, const string &word, int i, int j, vector<vector<char> > &board){
        if(k==word.size()-1 && board[i][j]==word[k])
            return true;
        if(board[i][j] != word[k])
            return false;
        char temp = board[i][j];
        // 走过的地方使用 '.'  来表示
        board[i][j] = '.';
        bool b1=false, b2=false, b3=false, b4=false;
        // board[i][j]的上面
        if(i>0 && board[i-1][j]!='.')
            b1 = helper(k+1, word, i-1, j, board);
        // board[i][j]的下面
        if(!b1 && i<board.size()-1 && board[i+1][j] != '.')
            b2 = helper(k+1, word, i+1, j, board);
        // board[i][j]的左面
        if(!b1 && !b2 && j>0 && board[i][j-1] != '.')
            b3 = helper(k+1, word, i, j-1, board);
        // board[i][j]的右面
        if(!b1 && !b2 && !b3 && j<board[0].size()-1 && board[i][j+1]!='.')
            b4 = helper(k+1, word, i, j+1, board);
        board[i][j] = temp;
        return b1 || b2 || b3 || b4;
    }
};

如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/30758751 )