码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Word Search 待解决?

时间:2015-05-14 20:32:34      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

 终于搞定了这个DFS,最近这个DFS写的很不顺手,我一直以为递归这种东西只是在解重构时比较麻烦,现在看来,连最简单的返回true和false的逻辑关系都不能说one hundred present 搞定。

人品啊TLE:

技术分享
 1 class Solution {
 2 public:
 3 bool legal(int i, int j, vector<vector<char>> board)
 4 {
 5     if (i >= 0 && i < board.size() && j >= 0 && j < board[i].size())
 6         return true;
 7     return false;
 8 }
 9 
10    bool dfs(vector<vector<char>>& board, string word, int t, int i, int j, vector<vector<bool>> visited)
11 {
12     if (t == word.length())
13         return true;
14     if (board[i][j] == word[t])
15     {
16         visited[i][j] = true;
17         if (legal(i - 1, j, board) && !visited[i - 1][j] && dfs(board, word, t + 1, i - 1, j, visited))
18             return true;
19         if (legal(i, j + 1, board) && !visited[i][j + 1] && dfs(board, word, t + 1, i, j + 1, visited))
20             return true;
21         if (legal(i + 1, j, board) && !visited[i + 1][j] && dfs(board, word, t + 1, i + 1, j, visited))
22             return true;
23         if (legal(i, j - 1, board) && !visited[i][j - 1] && dfs(board, word, t + 1, i, j - 1, visited))
24             return true;
25     }
26     visited[i][j] = false;
27     return false;
28 }
29 
30 bool exist(vector<vector<char>>& board, string word)
31 {
32     int m = board.size();
33     int n = board[0].size();
34     vector<vector<bool>> visited(m, vector<bool>(n, false));
35     for (int i = 0; i < board.size(); i++)
36     {
37         for (int j = 0; j < board[0].size(); j++)
38         {
39             if (dfs(board, word, 0, i, j, visited))
40                 return true;
41         }
42     }
43     return false;
44 }
45 };
View Code

 为什么?

leetcode Word Search 待解决?

标签:

原文地址:http://www.cnblogs.com/chaiwentao/p/4504233.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!