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

Word Search

时间:2015-09-02 00:01:04      阅读:163      评论: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 = 

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

 

Analyse: This problem has high time complexity. For each element in the 2D board, do the matching in four directions. If the length of searched elements equals to the string length, return true. If out of board index or the item doesn‘t equal to the corresponding string[i], return false. 

Runtime: 92ms

 1 class Solution {
 2 public:
 3     bool exist(vector<vector<char>>& board, string word) {
 4         if(board.empty() || board[0].empty()) return false;
 5         
 6         vector<vector<bool> > visited(board.size(), vector<bool>(board[0].size(), false));
 7         for(int i = 0; i < board.size(); i++){
 8             for(int j = 0; j < board[i].size(); j++){
 9                 if(dfs(board, word, visited, i, j, 0)) return true;
10             }
11         }
12         return false;
13     }
14     bool dfs(vector<vector<char> >& board, string word, vector<vector<bool> >& visited, int row, int col, int index){
15         if(index == word.length()) return true;
16         
17         if(row < 0 || col < 0 || row >= board.size() || col >= board[0].size() || visited[row][col] || word[index] != board[row][col])
18             return false;
19         
20         visited[row][col] = true;
21         if(dfs(board, word, visited, row + 1, col, index + 1)) return true;
22         if(dfs(board, word, visited, row - 1, col, index + 1)) return true;
23         if(dfs(board, word, visited, row, col + 1, index + 1)) return true;
24         if(dfs(board, word, visited, row, col - 1, index + 1)) return true;
25         visited[row][col] = false;
26         return false;
27     }
28 };

 

Word Search

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4776980.html

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