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

Leetcode: Word Search

时间:2014-12-07 01:17:40      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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。

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

 

Leetcode: Word Search

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4149038.html

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