79. 212. Word Search *HARD* -- 字符矩阵中查找单词

79. 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 =

[
  ['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 {
public:
    int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    
    bool isValid(int m, int n, int x, int y)
    {
        return x >= 0 && x < m && y >= 0 && y < n;
    }
    
    bool check(vector<vector<char>>& board, string word, int m, int n, int x, int y, int l, int k)
    {
        if(k == l)
            return true;
        if(!isValid(m, n, x, y) || board[x][y] != word[k])
            return false;
        int tx, ty, i, j;
        board[x][y] = '';
        for(i = 0; i < 4; i++)
        {
            tx = x + d[i][0];
            ty = y + d[i][1];
            if(check(board, word, m, n, tx, ty, l, k+1))
                return true;
        }
        board[x][y] = word[k];
        return false;
    }
    
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size(), l = word.length();
        if(0 == m || 0 == l)
            return false;
        int n = board[0].size(), i, j;
        for(i = 0; i < m; i++)
        {
            for(j = 0; j < n; j++)
            {
                if(check(board, word, m, n, i, j, l, 0))
                    return true;
            }
        }
        return false;
    }
};

212. Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must 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 in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

Return ["eat","oath"].

Note:
You may assume that all inputs are consist of lowercase letters a-z.

click to show hint.

You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?

If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.

class Solution {
public:
int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };

class Node
{
public:
    Node* ch[26];
    bool isWord;
    string word;
    Node()
    {
        memset(ch, 0, sizeof(ch));
        isWord = false;
        word = "";
    }
};

void createTree(vector<string>& words, Node *root)
{
    int n = words.size(), i;
    for (i = 0; i < n; i++)
    {
        Node *p = root;
        for (int j = 0; j < words[i].length(); j++)
        {
            if (p->ch[words[i][j] - 'a'] == NULL)
            {
                Node *t = new Node();
                p->ch[words[i][j] - 'a'] = t;
            }
            p = p->ch[words[i][j] - 'a'];
        }
        p->isWord = true;
        p->word = words[i];
    }
}

void find(vector<vector<char>>& board, Node *node, int x, int y, vector<string>& ans)
{
    int n = board.size(), m = board[0].size();
    if (x < 0 || x >= n || y < 0 || y >= m || board[x][y] == '')
        return;
    if (node->ch[board[x][y] - 'a'])
        node = node->ch[board[x][y] - 'a'];
    else
        return;
    if (true == node->isWord)
    {
        ans.push_back(node->word);
        node->isWord = false;
    }
    char c = board[x][y];
    board[x][y] = '';
    for (int i = 0; i < 4; i++)
    {
        int tx = x + dir[i][0], ty = y + dir[i][1];
        find(board, node, tx, ty, ans);
    }
    board[x][y] = c;
}

vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
{
    vector<string> ans;
    int n = board.size();
    if (n <= 0)
        return ans;
    Node *root = new Node();
    createTree(words, root);
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < board[0].size(); j++)
        {
            find(board, root, i, j, ans);
        }
    }
    return ans;
}
};
原文地址:https://www.cnblogs.com/argenbarbie/p/5805560.html