• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
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] = '\0';
        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] == '\0')
        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] = '\0';
    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;
}
};

 

posted on 2016-08-25 09:48  ArgenBarbie  阅读(175)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3