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

Word Search

时间:2014-08-23 15:07:40      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   使用   io   for   ar   div   

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.

思路:本题使用DFS求解即可。下面的解法假设输入word中不会包含‘#’这样的字符。

 1 class Solution {
 2 public:
 3     bool exist( vector<vector<char>> &board, string word ) {
 4         if( board.empty() ) { return word.empty(); }
 5         rows = board.size(), cols = board[0].size(), slen = word.length();
 6         for( int i = 0; i < rows; ++i ) {
 7             for( int j = 0; j < cols; ++j ) {
 8                 if( board[i][j] == word[0] && DFS( i, j, board, 0, word ) ) { return true; }
 9             }
10         }
11         return false;
12     }
13 private:
14     bool DFS( int i, int j, vector<vector<char>>& board, int index, const string& word ) {
15         if( ++index == slen ) { return true; }
16         board[i][j] = #;
17         if( i > 0 && board[i-1][j] == word[index] && DFS( i-1, j, board, index, word ) ) {
18             board[i][j] = word[index-1];
19             return true;
20         }
21         if( i < rows-1 && board[i+1][j] == word[index] && DFS( i+1, j, board, index, word ) ) {
22             board[i][j] = word[index-1];
23             return true;
24         }
25         if( j > 0 && board[i][j-1] == word[index] && DFS( i, j-1, board, index, word ) ) {
26             board[i][j] = word[index-1];
27             return true;
28         }
29         if( j < cols-1 && board[i][j+1] == word[index] && DFS( i, j+1, board, index, word ) ) {
30             board[i][j] = word[index-1];
31             return true;
32         }
33         board[i][j] = word[index-1];
34         return false;
35     }
36     int rows, cols, slen;
37 };

 

Word Search

标签:style   blog   color   os   使用   io   for   ar   div   

原文地址:http://www.cnblogs.com/moderate-fish/p/3930797.html

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