LeetCode 79. Word Search
2016-04-19 00:05
369 查看
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 =
word =
word =
// DFS. (compare it with BFS for better understanding.)
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.
// DFS. (compare it with BFS for better understanding.)
#include <vector> #include <iostream> #include <string> using namespace std; void checkValid(vector< vector<char> >& board, int i, int j, string word, int k, vector< vector<bool> >& visited, bool& found) { if(found) return; if(k == word.size()) {found = true; return;} vector< vector<int> > direction { {0, 1}, {0, -1}, {1, 0}, {-1, 0}}; for(int x = 0; x < direction.size(); ++x) { int nextPos_x = i + direction[x][0]; int nextPos_y = j + direction[x][1]; if(nextPos_x >= 0 && nextPos_x < board.size() && nextPos_y >= 0 && nextPos_y < board[i].size()) { if(!visited[nextPos_x][nextPos_y] && board[nextPos_x][nextPos_y] == word[k]) { visited[nextPos_x][nextPos_y] = true; checkValid(board, nextPos_x, nextPos_y, word, k + 1, visited, found); visited[nextPos_x][nextPos_y] = false; } } } } // construct letters of sequentially adjacent cell. bool exist(vector< vector<char> >& board, string word) { if(board.size() == 0) return false; if(board[0].size() == 0) return false; int m = board.size(); 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(board[i][j] == word[0]) { visited[i][j] = true; bool found = false; checkValid(board, i, j, word, 1, visited, found); if(found) return true; visited[i][j] = false; } } } return false; } int main(void) { vector< vector<char> > board { {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; bool found = exist(board, "BFCE"); cout << found << endl; }
相关文章推荐
- Android架构知识
- 二叉搜索树的后序遍历序列
- Spring 获取propertise文件中的值
- ASP.NET中CheckBoxList复选框列表控件详细使用方法
- ASP.NET中DropDownList下拉框列表控件绑定数据的4种方法
- ASP.NET中FileUpload文件上传控件应用实例
- yii2中的rules 自定义验证规则详解
- ThinkPHP中where()使用方法详解
- ThinkPHP中limit()使用方法详解
- ThinkPHP中order()使用方法详解
- 又拍云异步上传实例教程详解
- Python实现文件复制删除
- python安装与使用redis的方法
- python实现域名系统(DNS)正向查询的方法
- python实现简单socket通信的方法
- Python自动化部署工具Fabric的简单上手指南
- SQL Server 2016里的sys.dm_exec_input_buffer的问题
- SQL Server删除表及删除表中数据的方法
- 浅析JavaScript中浏览器的兼容问题
- jQuery实现选项联动轮播效果【附实例】