word Search
2015-12-01 22:29
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 = [ ['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E'] ]
word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.
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.
#include <vector> #include <string> #include <algorithm> #include <iostream> using namespace std; class Solution { public: bool exist(vector<vector<char>>& board, string word) { 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]){ if(dfs(i,j,0,board,word,visited)) return true; } } } return false; } bool dfs(int x,int y,int curr,vector<vector<char>>& board, string& word,vector<vector<bool>>& visited){ int m = board.size(); int n = board[0].size(); if(curr == word.size()) return true; if(x<0 || x>=m || y<0 || y>=n) return false; if(board[x][y] != word[curr]) return false; if(visited[x][y] == true) return false; visited[x][y] = true; bool ret= dfs(x, y+1, curr+1, board, word,visited) || dfs(x+1, y, curr+1, board, word,visited) || dfs(x, y-1, curr+1, board, word,visited) || dfs(x-1, y, curr+1, board, word,visited); visited[x][y] = false; return ret; } }; int main() { vector<vector<char>> board{{'a','a'}}; Solution s; cout << s.exist(board, "aaa") << endl; return 0; }
相关文章推荐
- timeSeries db之:使用Metrics监控应用程序的性能 (zz)
- 浏览器兼容的那些事(笔记)
- Android面试经验1
- 二叉搜索树(排序二叉树)
- 学习hamcrest和mockito时的总结和demo
- 正则表达式元字符
- Linux下select&poll&epoll的实现原理(一)
- 常用的算法思想总结
- ultraedit高亮显示设置
- 3644 - X-Plosives(水题,并差集)
- jQuery 简单笔记
- lodash用法系列(6),函数种种
- Java虚拟机10:类加载器
- 第二个Sprint冲刺第九天
- hdu-1237简单计算器(栈的运用)
- 二叉搜索树 POJ 2418 Hardwood Species
- CCNA 认证学习(一)
- SST-超级简单任务调度器结构分析
- 第二个spring冲刺第8天
- Elasticsearch 动态映射——自动检测