[Leetcode 79, Medium] Word Search
2015-07-24 21:28
375 查看
Problem:
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 =
word =
-> returns
word =
-> returns
word =
-> returns
Analysis:
Solutions:
C++:
Python:
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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word =
"ABCCED",
-> returns
true,
word =
"SEE",
-> returns
true,
word =
"ABCB",
-> returns
false.
Analysis:
Solutions:
C++:
bool SearchAux(vector<vector<char>>& board, const string& word, int search_index, int x, int y) { int size = word.size(); int rows = board.size(); int cols = board[0].size(); for(int i = -1; i <= 1; ++i) { for(int j = -1; j <= 1; ++j) { if((i == 0 && j !=0) || (i != 0 && j == 0)) { if(x + i < 0 || x + i >= rows || y + j < 0 || y +j >= cols || board[x + i][y + j] != word[search_index]) continue; if(search_index == word.size() - 1) return true; board[x + i][y + j] = '#'; if(SearchAux(board, word, search_index + 1, x + i, y + j)) return true; board[x + i][y + j] = word[search_index]; } } } return false; } bool exist(vector<vector<char>>& board, string word) { if(board.empty() || word.empty()) return false; vector<pair<int, int> > starts; for(int i = 0; i < board.size(); ++i) { for(int j = 0; j < board[0].size(); ++j) { if(board[i][j] == word[0]) starts.push_back(make_pair(i, j)); } } if(word.size() == 1 && starts.size() > 0) return true; for(int i = 0; i < starts.size(); ++i) { board[starts[i].first][starts[i].second] = '#'; if(SearchAux(board, word, 1, starts[i].first, starts[i].second)) return true; board[starts[i].first][starts[i].second] = word[0]; } return false; }Java:
Python:
相关文章推荐
- 单片机---串口打印字符串时,只显示第一个字符
- Android事件处理
- Leetcode Shortest Palindrome (最短回文串)
- How to Compile Java DBus
- [leedcode 126] Word Ladder
- 平衡的括号(名字怪怪的~)
- 关于shell排序
- Day_02_数据库的简单连接和添加数据
- 默默重新开始,第一页也是新的一页
- 自动机,状态机,有限自动机,有限状态机,有限状态自动机,非确定下有限状态自动,确定性有限状态自动机的区别于联系
- Project Euler:Problem 90 Cube digit pairs
- 它们的定义android滑动菜单
- android 加载大图片防止内存溢出
- IOS html解析
- java 命令行参数输入法的应用
- Spark性能优化的10大问题及其解决方案
- 方格取数(1)(HDU 1565状压dp)
- JAVA中的String连接性能
- 【剑指offer】1.赋值运算符函数
- Java设计模式之单例模式