leetcode 日经贴,python code -Word Search II
2015-08-10 18:59
651 查看
Word Search II
struct TrieNode { TrieNode (){ memset(next, 0, sizeof(next)); id = -1; count = 0; } TrieNode* next[26]; int id, count; }; class Solution { public: Solution() { root = new TrieNode(); } vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { vector<string> ans; int R = board.size(); if (!R) { return ans; } int C = board[0].size(); if (!C) { return ans; } sort(words.begin(), words.end()); int wordslen = words.size(); if (!wordslen) { return ans; } for (int i = 0; i < wordslen; ++i) { //did't insert the same word twice if (i == 0 || words[i] != words[i - 1]) { insert(words[i].c_str(), i); } } vector<vector<bool> > visit(R); for (int i = 0; i < R; ++i) { visit[i].resize(C); } vector<int> matchids; for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { match(root, board, visit, R, C, i, j, matchids); } } sort(matchids.begin(), matchids.end()); for (int i = 0; i < matchids.size(); ++i) { ans.push_back(words[matchids[i]]); } return ans; } private: TrieNode* root; const static int dir[4][2]; void insert(const char* s, int id) { TrieNode* p = root; p->count++; while (*s) { if (!p->next[*s - 'a']) { p->next[*s - 'a'] = new TrieNode(); } p = p->next[*s - 'a']; p->count++; ++s; } p->id = id; } int match(TrieNode* cur, vector<vector<char> >& board, vector<vector<bool> >& visit, int R, int C, int r, int c, vector<int>& matchids) { if (!cur) { return 0; } int child = board[r][c] - 'a'; if (!cur->next[child]) { return 0; } TrieNode* next = cur->next[child]; int matchcnt = 0; if (next->id != -1) { matchids.push_back(next->id); if (next->count == 1) { delete next; cur->next[child] = NULL; return 1; } else { matchcnt++; next->id = -1; } } visit[r][c] = true; for (int d = 0; d < 4; ++d) { int nr = r + dir[d][0]; int nc = c + dir[d][1]; if (nr >= 0 && nr < R && nc >= 0 && nc < C && !visit[nr][nc]) { matchcnt += match(next, board, visit, R, C, nr, nc, matchids); } } visit[r][c] = false; if (next->count - matchcnt == 0) { delete next; cur->next[child] = NULL; } else { next->count -= matchcnt; } return matchcnt; } }; const int Solution::dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
相关文章推荐
- python中利用lxml模块解析xml文件报错XMLSyntaxError: Opening and ending tag mismatch
- 今天看项目和框架的一些小知识
- [Python学习] 模块三.基本字符串
- 耗子学Python了(1)___Python环境配置
- python 常用string函数
- python-装饰器的学习
- 运行一个python项目的步骤
- 人生苦短,喝点python性能鸡汤
- python的内置函数
- Python安装cairo、gtk等问题
- Python学习-第一天
- PYTHON-mysql fetchall和 fetchone之间的区别
- python中的exec()函数的作用
- python 基础教程
- 使用国内镜像源来加速python pypi包的安装
- 国内的pythoner强烈建议使用豆瓣的pypi源 zz
- Python之Window环境搭建
- python基础
- Python入门 Dict和Set类型
- Python下opencv使用笔记