【leetcode】Word Search

Word Search

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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
 
 
 1 class Solution {
 2 public:
 3  
 4  
 5     int n,n1,n2;
 6  
 7    
 8     bool exist(vector<vector<char> > &board, string word) {
 9        
10         n1=board.size();
11         n2=board[0].size();
12         n=word.length();
13        
14         bool flag=false;
15        
16         //vector<vector<bool> > visited(n1,vector<bool>(n2,false));
17        
18         bool **visited=new bool*[n1];
19         for(int i=0;i<n1;i++)
20         {
21             visited[i]=new bool[n2];
22             for(int j=0;j<n2;j++)
23             {
24                 visited[i][j]=false;
25             }
26         }
27        
28        
29        
30         for(int i=0;i<n1;i++)
31         {
32             for(int j=0;j<n2;j++)
33             {
34                 if(board[i][j]==word[0])
35                 {
36                     //注意visited采用引用传值
37                     flag=flag||dfs(board,word,i,j,visited);
38                     if(flag) return true;
39                 }
40             }
41         }
42        
43        
44         for(int i=0;i<n1;i++) delete[] visited[i];
45        
46         return false;
47     }
48    
49  
50     bool dfs(vector<vector<char> > &board,string &word,int i,int j,bool** &visited,int index=0)
51     {
52  
53         if(board[i][j]!=word[index]||visited[i][j]) return false;
54         if(index==n-1) return true;
55        
56         visited[i][j]=true;
57        
58         bool flag1=i+1<n1&&dfs(board,word,i+1,j,visited,index+1);
59         bool flag2=j+1<n2&&dfs(board,word,i,j+1,visited,index+1);
60         bool flag3=j-1>=0&&dfs(board,word,i,j-1,visited,index+1);
61         bool flag4=i-1>=0&&dfs(board,word,i-1,j,visited,index+1);
62        
63         bool result=flag1||flag2||flag3||flag4;
64        
65         //由于是引用传值,所以没有找到的目标串时要把visited复原
66         //if(result==false) visited[i][j]=false;         
67         visited[i][j]=result;
68         return result;          
69     }
70 };

 

 
 
 
 
posted @ 2015-01-03 19:31  H5开发技术  阅读(162)  评论(0编辑  收藏  举报