zoukankan      html  css  js  c++  java
  • LeetCode 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 Node {
    public:
        Node* child[26];
        int count;
    
        Node() {
            count=0;
            for (int i=0; i<26; i++) {
                child[i] = NULL;
            }
        }
    };
    
    class Trie {
    private:
        Node root;
        static void insert_aux(Node* node, const char* s, int idx, int len) {
            if (node == NULL) {
                return;
            }
            if (idx == len) {
                node->count++;
                return;
            }
            char ch = s[idx] - 'a';
            if (node->child[ch] == NULL) {
                node->child[ch] = new Node();
            }
            insert_aux(node->child[ch], s, idx + 1, len);
        }
    
        static Node* search(Node* node, const char* str, int len, int idx) {
            if (node == NULL || str == NULL) {
                return NULL;
            }
            if (len == idx) {
                return node;
            }
            Node* ch = node->child[str[idx] - 'a'];
            return search(ch, str, len, idx + 1);
        }
    public:
        void insert(string word) {
            insert_aux(&root, word.c_str(), 0, word.size());
        }
    
        void insert(const char* str, int len) {
            insert_aux(&root, str, 0, len);
        }
    
        Node* search(string word) {
            return search(word.c_str(), word.size());
        }
    
        static Node* search(Node* node, char* str, int len) {
            return search(node, str, len, 0);
        }
    
        Node* search(const char* str, int len) {
            return search(&root, str, len, 0);
        }
        
        Node* getRoot() { return &root;}
    };
    
    
    class Solution {
    private:
        vector<string> res;
    public:
        vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
            res.clear();
            
            int rows = board.size();
            if (rows < 1) {
                return res;
            }
            int cols = board[0].size();
            if (cols < 1) {
                return res;
            }
            
            // initialize trie for fast word prefix lookup
            Trie trie;
            for (string& s : words) {
                trie.insert(s);
            }
            string path;
            for (int i=0; i<rows; i++) {
                for (int j=0; j<cols; j++) {
                    dfs(board, j, i, trie.getRoot(), path);        
                }
            }
            
            return res;
        }
        
        void dfs(vector<vector<char> >& board, int x, int y, Node* node, string& path) {
            if (node == NULL) {
                return;
            } else if (node->count > 0){
                res.push_back(path);
                // so we won't add one word more than once.
                node->count = 0;
            }
            
            int rows = board.size();
            int cols = board[0].size();
            
            if (x >= cols || x < 0 || y >= rows || y < 0) {
                return;
            }
            char ch = board[y][x];
            // current position is in dfs path, so don't search again
            if (ch == 0) {
                return;
            }
            
            Node* next = node->child[ch - 'a'];
            // mark on board
            board[y][x] = 0;
            path.push_back(ch);
    
            int dx[] = {1, 0, -1, 0};
            int dy[] = {0, 1, 0, -1};
            for (int i=0; i<4; i++) {
                dfs(board, x + dx[i], y + dy[i], next, path);
            }
            // restore character
            path.pop_back();
            board[y][x] = ch;
        }
    };

    先写了个字典树,有专门的实现字典树的题目,做过一次顺利许多。dfs内部的一些判断可以提前进行,不过为了形式上整齐一些没有这样做

  • 相关阅读:
    word2vector 资料
    回声状态网络(ESN)基础教程
    GBDT:梯度提升决策树
    B-树,B+树,B*树详解
    HTTP权威指南-基础知识
    JavaScript高级程序设计--对象,数组(栈方法,队列方法,重排序方法,迭代方法)
    HTML自定义对象与属性探究(谷歌,火狐,IE9浏览器没问题)
    冒泡,setinterval,背景图的div绑定事件,匿名函数问题探究
    JavaScript高级程序设计--表单脚本
    我是跨域的JSONP
  • 原文地址:https://www.cnblogs.com/lailailai/p/4573927.html
Copyright © 2011-2022 走看看