Word Search
来源:互联网 发布:淘宝女装店铺描述范文 编辑:程序博客网 时间:2024/06/05 20:13
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.
图的DFS搜索+回溯。
设置dir[4][2]作为移动方向。
int maxdep, m, n;int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};bool dfs(string word, int dep, vector<vector<char> > &board, int x, int y, vector<vector<bool> > &visit){ if (dep == maxdep) return true; for (int i = 0; i < 4; i++) { int xx = x + dir[i][0]; int yy = y + dir[i][1]; if (xx >= 0 && xx < m && yy >= 0 && yy < n && board[xx][yy] == word[dep] && !visit[xx][yy]) { visit[xx][yy] = true; if (dfs(word, dep+1, board, xx, yy, visit)) return true; visit[xx][yy] = false; } }}bool exist(vector<vector<char> > &board, string word){ if (word.size()==0) return true; if (board.size()==0) return false; maxdep = word.size(); m = board.size(); n = board[0].size(); vector<vector<bool> > visit(m, vector<bool>(n, false)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (word[0] == board[i][j]) { visit[i][j] = true; if (dfs(word, 1, board, i, j, visit)) return true; visit[i][j] = false; } } } return false;}
0 0
- Word Search
- Word Search
- word search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- 字符设备驱动linux2.6
- Hadoop集群(第8期)_HDFS初探之旅
- vector
- Git 工作区、暂存区和版本库
- 用javascript实现水印的效果
- Word Search
- 一步一步学Nagios安装部署与监控
- 随转觉得还不错
- 经纬财富:荆门金价是否继续走强
- POJ 2482 Stars in Your Window
- 数据分类那些事儿
- iOS 找到视图的第一响应者
- Dynamic Web TWAIN使用教程:创建网页扫描程序
- HDU4474 Yet Another Multiple Problem