126_leetcode_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.

1:注意特殊情况;2:设置二维数组保存当前字符是不是已经使用过了。3:遍历数组,数组中的每个字符与单词的首字符相比较,如果相等的话,进行递归;4:注意递归结束情况,以及返回情况

    bool exist(vector<vector<char> > &board, string word)
    {
        if(word.size() == 0 || board.size() == 0 || board[0].size() == 0)
        {
            return false;
        }
        
        int rows = (int)board.size();
        int columns = (int)board[0].size();
        int length = (int)word.size();
        if(length > rows * columns)
        {
            return false;
        }
        
        vector<vector<bool> > flag(rows, vector<bool>(columns, false));
        
        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < columns; j++)
            {
                if(board[i][j] == word[0])
                {
                    if(existCore(board, i, j, word, 1, flag))
                    {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
    
    bool existCore(vector<vector<char> > &board, int curX, int curY, string &word, int index, vector<vector<bool> > &flag)
    {
        if(word[index] == '\0')
        {
            return true;
        }
        
        flag[curX][curY] = true;
        
        bool result = false;
        
        if(curX - 1 >= 0 && flag[curX-1][curY] == false && board[curX-1][curY] == word[index])
        {
            result = existCore(board, curX-1, curY, word, index + 1, flag);
        }
        
        if(!result && curX + 1 < (int)board.size() && flag[curX+1][curY] == false && board[curX + 1][curY] == word[index])
        {
            result = existCore(board, curX + 1, curY, word, index + 1 , flag);
        }
        
        if(!result && curY - 1 >= 0 && flag[curX][curY-1] == false && board[curX][curY - 1] == word[index])
        {
            result = existCore(board, curX, curY - 1, word, index + 1, flag);
        }
        
        if(!result && curY + 1 < (int)board[curX].size() && flag[curX][curY + 1] == false && board[curX][curY + 1] == word[index])
        {
            result =  existCore(board, curX, curY + 1, word, index + 1, flag);
        }
        
        flag[curX][curY] = false;
        
        
        return result;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章