题目描述:

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.

解题思路:

我的思路是先在二维数组中搜索与字符串第一个匹配的字符,然后接下的工作就是在这个字符的四边寻找第二个匹配的字符,以此类推。这个工作我是用递归来实现,最后的返回条件是当字符读到最后一个且匹配的时候。但有一点要注意,一次匹配过的字符不能再次匹配,就像第三个例子一样,所以我将匹配过的字符变成NULL。

代码:

 1 class Solution {
 2 public:
 3     bool check(vector<vector<char>> board, string &word, int index, int row, int col){
 4         if(index == word.size())//返回条件
 5             return true;
 6         if(row < 0 || row >= board.size() || col < 0 || col >= board[0].size())//防止数组越界
 7             return false;
 8         if(board[row][col] == word[index]){//匹配
 9             board[row][col] = NULL;
10             return check(board, word, index+1, row-1, col)||check(board, word, index+1, row+1, col)||check(board, word, index+1, row, col-1)||check(board, word, index+1, row, col+1);//搜索四周
11         }
12         return false;//不匹配
13     }
14     bool exist(vector<vector<char>>& board, string word) {
15         int rowN = board.size();
16         if(rowN == 0)
17             return false;
18         int colN = board[0].size();
19         for(int i = 0; i < rowN; i++){//搜索第一个匹配字符
20             for(int j = 0; j < colN; j++){
21                 if(check(board, word, 0, i, j))
22                     return true;
23             }
24         }
25         return false;
26     }
27 };

 

posted on 2018-03-16 20:10  宵夜在哪  阅读(107)  评论(0编辑  收藏  举报