DFS Word Search
2015-05-10 16:09
169 查看
思想:
DFS
DFS
class Solution { private: //Word Search int dir[4][2] = { { 0,-1},//left { 0, 1},//right {-1, 0},//top { 1, 0},//down }; const int DIR = 4; bool rangeOK(vector<vector<char>> &board,int x,int y) { const size_t m = board.size(); const size_t n = board[0].size(); if(x<0 || x>m-1 || y<0 || y>n-1) return false; else return true; } bool dfs(vector<vector<char>> &board, string word, vector<vector<bool>> &map, int x, int y, int loc) { if(loc == word.size()) return true; if(!rangeOK(board, x, y)) return false; if(map[x][y]) return false; if(board[x][y] != word[loc]) return false; map[x][y] = true; for(int i=0;i<DIR;i++) { int xx = x + dir[i][0]; int yy = y + dir[i][1]; bool ret = dfs(board, word, map, xx, yy, loc+1); if(ret == true) return true; } map[x][y] = false; return false; } public: bool exist(vector<vector<char>>& board, string word) { const size_t m = board.size(); const size_t n = board[0].size(); vector<vector<bool>> map = vector<vector<bool>>(m,vector<bool>(n,false)); for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { if(dfs(board,word,map,i,j,0)) { return true; } } } return false; } };
相关文章推荐
- Word Search DFS注意回溯
- LeetCode 79 Word Search (DFS)
- 【两类dfs总结】 Restore IP Addresses、Word Search、Subsets、带重复的全排列
- Word Search(深度搜索DFS,参考)
- *LeetCode 79. Word Search DFS
- leetcode 79. Word Search DFS 单词搜索 + 深度优先遍历
- word search 此题若会,所有dfs矩阵全会
- 79. Word Search (Graph; DFS)
- 矩阵中的路径--79 word Search--DFS回溯
- 哈理工OJ 1743 Word Search (深搜dfs)
- hrbust 哈理工oj 1743 Word Search【DFS过】
- PKU2688 Cleaning Robot(BFS + DFS)
- poj Sudoku(数独) DFS
- HDU_2196_Computer(树上节点的最长路径 · dfs / bfs)
- hdu5950 dfs
- (M)DFS:473. Matchsticks to Square
- zju1798 Granny's Bike (DFS)
- dfs 和 bfs 解析
- hdoj 1427 速算24点 【经典 dfs 】
- 51nod 1400 序列分解【Dfs+剪枝】好题~