【leetcode】79. Word Search
2015-10-08 20:05
489 查看
简单的dfs
/** * @author johnsondu * @time 20:01 8th Oct 2015 * @type dfs * @url https://leetcode.com/problems/word-search/ * @status Accepted */ class Solution { public: void dfs(int x, int y, int idx, int len, int row, int col, vector<vector<bool>> &mark, bool &flag, vector<vector<char>>& board, string word) { if(flag) return; if(word[idx] != board[x][y]) return; if(idx == len - 1) { flag = true; return; } int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1}; for(int k = 0; k < 4; k ++) { int tx = x + dir[k][0]; int ty = y + dir[k][1]; if(tx >= row || ty >= col || tx < 0 || ty < 0) continue; if(mark[tx][ty]) continue; mark[tx][ty] = true; dfs(tx, ty, idx + 1, len, row, col, mark, flag, board, word); mark[tx][ty] = false; } } bool exist(vector<vector<char>>& board, string word) { if(board.size() == 0) return false; if(word.size() == 0) return true; int row = board.size(); int col = board[0].size(); vector<vector<bool>> mark(board.size(), vector<bool>(board[0].size(), false)); bool flag = false; int len = word.size(); for(int i = 0; i < row; i ++) { for(int j = 0; j < col; j ++) { if(board[i][j] == word[0]) { mark[i][j] = true; dfs(i, j, 0, len, row, col, mark, flag, board, word); mark[i][j] = false; if(flag) return flag; } } } return flag; } };
相关文章推荐
- Dialog中有EditText无法弹出输入法解决方法
- 数据结构实验之栈六:下一较大值(二)【OJ-3333】【自己写的封装的栈代码】
- 自居电路(升压电路)
- 关于AlertDialog的常见用法
- 海量数据处理分析
- 编辑并保存手机中的图片至本地
- Linux CP文件夹略过目录的解决
- leecode algo4: Median of Two Sorted Arrays (Java)
- 什么是Kivy???
- Windows Azure Virtual Machine (26) 使用高级存储和DS系列VM
- 在service中播放音乐
- [BNU弱校联萌]背水一战
- C++_中的不可变类
- MyBatis与Hibernate对比
- Python中的单引号,双引号和三双引号
- Codeforces Round #324 (Div. 2)D. Dima and Lisa 数学(素数)
- [NOIP2004]虫食算 T4
- iscsi的安装
- 从数据读图片保存到imageList里面
- 简易Session版购物车