leetcode79——Word Search
来源:互联网 发布:linux ls 隐藏文件 编辑:程序博客网 时间:2024/05/20 07:19
Word Search
/*Word SearchGiven 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.*/#include<iostream>#include<vector>using namespace std;class Solution {public:bool exist(vector<vector<char> > &board, string word) {const int m = board.size();const int n = board[0].size();vector<vector<bool> > visited(m, vector<bool>(n, false));for (int i = 0; i < m; ++i)for (int j = 0; j < n; ++j)if (dfs(board, word, 0, i, j, visited))return true;return false;}private:static bool dfs(const vector<vector<char> > &board, const string &word,int index, int x, int y, vector<vector<bool> > &visited) {if (index == word.size())return true;// 收敛条件if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size())return false;// 越界,终止条件if (visited[x][y]) return false;// 已经访问过,剪枝if (board[x][y] != word[index]) return false;// 不相等,剪枝visited[x][y] = true;bool ret = dfs(board, word, index + 1, x - 1, y, visited) ||// 上dfs(board, word, index + 1, x + 1, y, visited) ||// 下dfs(board, word, index + 1, x, y - 1, visited) ||// 左dfs(board, word, index + 1, x, y + 1, visited);// 右visited[x][y] = false;return ret;}};int main(){vector<vector<char> > board;string word="SEE";char m;for(int i=0;i<3;i++){vector<char> b;for(int j=0;j<4;j++){//b.clear();cin>>m;b.push_back(m);}board.push_back(b);}Solution eg; cout<<eg.exist(board,word)<<endl;for(int i=0;i<3;i++){for(int j=0;j<4;j++)cout<<board[i][j];cout<<endl;}cout<<endl;return 0;}
0 0
- leetcode79——Word Search
- LeetCode79——Word Search
- LeetCode79:Word Search
- leetcode79. Word Search
- LeetCode79 Word Search
- leetcode79 word serach 解题报告
- [LeetCode]—Word Search
- LeetCode —— Word Search
- LeetCodeOJ——Word Search
- leetcode——Word Search
- Algorithms—79.Word Search
- leetcode 079 —— Word Search
- 【leetcode】Array——word search(79)
- LeetCode——79. Word Search
- LeetCode—212 Word Search II
- leetcode——79—— Word Search
- leetcode——Add and Search Word - Data structure design
- LeetCode刷题(C++)——Word Search(Medium)
- 深入理解Executor
- 2014求职记(二)
- 泰格至尊版软件加密锁注册机
- 机器学习工具包
- Mahout学习之Mahout安装、配置、入门程序测试
- leetcode79——Word Search
- Servlet和JDBC的登陆实现应用
- Matlab中 pdist 函数详解(各种距离的生成)
- hdu 4747 线段树
- 关于 struts+ajax+jquery 验证用户名是否重复
- ZOJ_3593_One person game_扩展欧几里德
- C++中const的实现机制深入分析
- 黑马程序员:iOS基础——个人笔记(五)
- C++函数中那些不可以被声明为虚函数的函数