首页 > 其他 > 详细

word Search

时间:2015-12-01 23:09:21      阅读:325      评论:0      收藏:0      [点我收藏+]

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.

 1 #include <vector>
 2 #include <string>
 3 #include <algorithm>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     bool exist(vector<vector<char>>& board, string word) {
10         int m = board.size();
11         int n = board[0].size();
12         
13         vector<vector<bool>> visited(m,vector<bool>(n,false));
14         for(int i=0;i<m;i++){
15             for(int j=0;j<n;j++){
16                 if(board[i][j] == word[0]){
17                     if(dfs(i,j,0,board,word,visited))
18                         return true;
19                 }
20             }
21         }
22         return false;
23     }
24 
25     bool dfs(int x,int y,int curr,vector<vector<char>>& board,
26         string& word,vector<vector<bool>>& visited){
27 
28         int m = board.size();
29         int n = board[0].size();
30 
31         if(curr == word.size())  return true;
32 
33         if(x<0 || x>=m || y<0 || y>=n) return false;
34 
35         if(board[x][y] != word[curr])  return false;
36 
37         if(visited[x][y] == true) return false;
38 
39         visited[x][y] = true;
40         bool ret= dfs(x, y+1, curr+1, board, word,visited) ||
41                dfs(x+1, y, curr+1, board, word,visited) ||
42                dfs(x, y-1, curr+1, board, word,visited) ||
43                dfs(x-1, y, curr+1, board, word,visited);
44         visited[x][y] = false;
45         return ret;
46     }
47 };
48 
49 int main()
50 {
51 
52     vector<vector<char>> board{{a,a}};
53     Solution s;
54     cout << s.exist(board, "aaa") << endl;
55     return 0;
56 
57 }

 

word Search

原文:http://www.cnblogs.com/wxquare/p/5011538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!