LeetCode-Word Search

来源:互联网 发布:一起来做淘宝 编辑:程序博客网 时间:2024/06/05 21:53

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.

Solution:

Code:

<span style="font-size:14px;">class Solution {public:    bool helper(vector<vector<char> > &board, const int &rows, const int &cols, int row, int col, vector<vector<bool> > &checked, const string &word,                     const int &length, int index) {        if (index == length) return true;        if (row < 0 || col < 0 || row >= rows || col >= cols) return false;        if (checked[row][col] || board[row][col] != word[index]) return false;        checked[row][col] = true;        if (helper(board, rows, cols, row-1, col, checked, word, length, index+1) ||            helper(board, rows, cols, row+1, col, checked, word, length, index+1) ||            helper(board, rows, cols, row, col-1, checked, word, length, index+1) ||            helper(board, rows, cols, row, col+1, checked, word, length, index+1))            return true;        checked[row][col] = false;        return false;    }        bool exist(vector<vector<char> > &board, string word) {        int length = word.size();        if (length == 0) return true;        int rows = board.size();        if (rows == 0) return false;        int cols = board[0].size();        vector<vector<bool> > checked(rows, vector<bool>(cols, false));        for (int row = 0; row < rows; row++)            for (int col = 0; col < cols; col++)                if (helper(board, rows, cols, row, col, checked, word, length, 0))                    return true;        return false;    }};</span>


0 0
原创粉丝点击