leetcode第一刷_Word Search
来源:互联网 发布:淘宝掌柜名称怎么修改 编辑:程序博客网 时间:2024/06/05 15:18
这道题之前一直没敢做,没想到前天用递归一遍过了。。
当时为什么想着用递归,而不是dp呢,因为我想到达某个位置的情况有很多,即使从当前位置开始的搜索是已知的,但之前的状态是怎样的也无从得知啊,实话实说,我是不会用dp解这个。。
递归的思路就好说多了,从当前点开始,有上下左右四个位置可以探测,如果探测成功的话,要把当前的位置用其他符号标记出来,以免重复访问。实际上就是DFS嘛,只不过入口多一些。
需要注意的一点是,每个点都可以作为起点,所以这个要穷举一下,否则会漏掉情况的。当然有一种情况走通就可以返回了,剪枝之。
代码又臭又长,不过work:
class Solution {public: int row, column; bool doexist(vector<vector<char> > &board, string &word, int len, int i, int j){ if(len == word.length()) return true; bool res; if(i>0&&board[i-1][j] == word[len]){ board[i-1][j] = '.'; res = doexist(board, word, len+1, i-1, j); if(res) return true; else board[i-1][j] = word[len]; } if(i<row-1&&board[i+1][j] == word[len]){ board[i+1][j] = '.'; res = doexist(board, word, len+1, i+1, j); if(res) return true; else board[i+1][j] = word[len]; } if(j>0&&board[i][j-1] == word[len]){ board[i][j-1] = '.'; res = doexist(board, word, len+1, i, j-1); if(res) return true; else board[i][j-1] = word[len]; } if(j<column-1&&board[i][j+1] == word[len]){ board[i][j+1] = '.'; res = doexist(board, word, len+1, i, j+1); if(res) return true; else board[i][j+1] = word[len]; } return false; } bool exist(vector<vector<char> > &board, string word) { row = board.size(); if(row == 0) return false; column = board[0].size(); char c; for(int i=0;i<row;i++){ for(int j=0;j<column;j++){ if(board[i][j] == word[0]){ board[i][j] = '.'; if(doexist(board, word, 1, i, j)) return true; board[i][j] = word[0]; } } } return false; }};
0 0
- leetcode第一刷_Word Search
- leetcode第一刷_Word Break
- leetcode第一刷_Word Ladder
- leetcode第一刷_Word Break II
- leetcode第一刷_Word Ladder II
- leetcode第一刷_Recover Binary Search Tree
- leetcode第一刷_Validate Binary Search Tree
- leetcode第一刷_Unique Binary Search Trees
- leetcode第一刷_Convert Sorted List to Binary Search Tree
- leetcode第一刷_Convert Sorted Array to Binary Search Tree
- leetcode第一刷_Unique Binary Search Trees II
- leetcode第一刷_Candy
- leetcode第一刷_Triangle
- leetcode第一刷_Combinations
- leetcode第一刷_Anagrams
- leetcode第一刷_Permutations
- leetcode第一刷_Triangle
- leetcode第一刷_3Sum
- AngularJs学习笔记--Managing Service Dependencies
- UML类图几种关系的总结
- Mac移动硬盘
- gdb server 远程调试
- sysctl使用方法的变化
- leetcode第一刷_Word Search
- UML用例图总结
- nginx+phpfpm+mysql维护
- linux下安装mysql
- HDU 1281-二分图求最大匹配+删边判断
- 等频直方图预估结果集行计算公式
- CSS层叠样式表
- 有关loadDataWithBaseURL的讲解
- 分享:matlab实现车牌字符分割与识别