LeetCode : Word Search

来源:互联网 发布:2017php笔试 编辑:程序博客网 时间:2024/04/27 12:16

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.

要考虑输入是 ["aa"], "aaa"的问题。

class Solution {public:    bool exist(vector<vector<char> > &board, string word) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int nRow = board.size();        if(nRow == 0) return false;        if(word.size() == 0) return true;        int nCol = board[0].size();        bool res = false;        for(int i = 0; i< nRow; ++i){            for(int j = 0; j< nCol; ++j)            {                if(board[i][j] == word[0]){                    board[i][j] = 0;                    res = sub(board, word.substr(1), i, j);                    board[i][j] = word[0];                    if(res)                        return res;                }            }        }        return res;    }    bool sub(vector<vector<char> > &board, string word, int row, int col){        if(word.size() == 0) return true;        char c = word[0];        int nRow = board.size();        int nCol = board[0].size();        bool res = false;        if(row -1 >= 0 &&board[row-1][col] == c){            board[row-1][col] = 0;            res = sub(board, word.substr(1), row - 1, col);            board[row-1][col] = c;            if(res)                return true;        }        if(row + 1 < nRow && board[row + 1][col] == c){            board[row+1][col] = 0;            res = sub(board, word.substr(1), row + 1, col);            board[row+1][col] = c;            if(res)                return true;        }        if(col - 1 >= 0 && board[row][col - 1] == c){            board[row][col - 1] = 0;            res = sub(board, word.substr(1), row, col - 1);            board[row][col - 1] = c;            if(res)                return true;        }        if(col + 1 < nCol && board[row][col + 1] == c){            board[row][col + 1] = 0;            res = sub(board, word.substr(1), row, col + 1);            board[row][col + 1] = c;            if(res)                return true;        }        return false;    }};


原创粉丝点击