79. Word Search

来源:互联网 发布:北京用友软件代理商 编辑:程序博客网 时间:2024/06/07 08:48

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 =

[  ['A','B','C','E'],  ['S','F','C','S'],  ['A','D','E','E']]

输出

word = "ABCCED", -> returns true,word = "SEE", -> returns true,word = "ABCB", -> returns false.

解题代码

class Solution {private:    int m, n; // m行,n列    // 上右下左4个方向的偏移    int direction[4][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };    vector<vector<bool>> visited;    bool isInArea(int x, int y){        return x >= 0 && x < m && y >= 0 && y < n;    }    // 在board中从点(startX,startY)开始寻找word[index,word.size()-1]是否存在    bool searchWord(const vector<vector < char >> &board, const string &word, int index, int startX, int startY){        // 递归终止,当前要找的是word的最后一个        if (index == word.size() - 1){            return board[startX][startY] == word[index];        }        if (board[startX][startY] == word[index])        for (int i = 0; i < 4; i++)        {            // 标记当前位置已经访问            visited[startX][startY] = true;            // 分情况递归过程,下一状态(也就是下一位置寻找)是上右下左四个方向走            int nextX = startX + direction[i][0];            int nextY = startY + direction[i][1];            // 对下一位置进行访问,满足下面三个条件则true            if (isInArea(nextX, nextY) &&                 !visited[nextX][nextY] &&                 searchWord(board, word, index + 1, nextX, nextY))                return true;            // 递归回溯,放弃访问这个位置            visited[startX][startY] = false;        }        return false;    }public:    bool exist(vector<vector<char>>& board, string word) {        // 初始参数        m = board.size();        assert(m > 0);        n = board[0].size();        visited = vector <vector<bool>>(m, vector<bool>(n, false));        for (int i = 0; i < board.size(); i++)        for (int j = 0; j < board[i].size(); j++)        if (searchWord(board, word, 0, i, j))            return true;        return false;    }};
原创粉丝点击