Leetcode 212. Word Search II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Word Search II

2. Solution

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> result;
        int rows = board.size();
        int columns = board[0].size();
        unordered_set<string> s;
        for(string word : words) {
            s.insert(word);
        }
        for(string word : s) {
            if(rows * columns < word.length()) {
                continue;
            }
            if(exist(board, word, rows, columns)) {
                result.push_back(word);
            }
        }
        return result;
    }
    
private:
    bool exist(vector<vector<char>>& board, string& word, int& rows, int& columns) {
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                if(board[i][j] == word[0] && search(board, word, i, j, 0, rows, columns)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    
    bool search(vector<vector<char>>& board, string& word, int i, int j, int current, const int& rows, const int& columns) {
        if(i < 0 || i == rows || j < 0 || j == columns || board[i][j] != word[current]) {
            return false;
        }
        board[i][j] -= 60;
        current += 1;
        if(current == word.length()) {
            board[i][j] += 60;
            return true;
        }
        bool result = search(board, word, i + 1, j, current, rows, columns) 
                || search(board, word, i - 1, j, current, rows, columns) 
                || search(board, word, i, j + 1, current, rows, columns) 
                || search(board, word, i, j - 1, current, rows, columns);
        board[i][j] += 60;
        return result;
    }
    
};

Reference

  1. https://leetcode.com/problems/word-search-ii/description/
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容