首页 > 其他 > 详细

Leetcode Word Search

时间:2014-07-05 21:30:26      阅读:336      评论: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

 本题用深度搜索即可

 

class Solution {
public:
    typedef vector<vector<bool> > VVB;
    typedef vector<vector<char> > VVC;
    
    const int dx[4] = {0,1,0,-1};
    const int dy[4] = {1,0,-1,0};
    
    int n,m;
    VVC board;
    string word;
    
    bool dfs(int x, int y,int index,VVB &visit){
        if(index == word.length()) return true;
        if(x>=0 && x <n && y>=0 && y < m && !visit[x][y] && board[x][y] == word[index]){
            visit[x][y] = true;
            for(int i = 0 ; i < 4; ++ i){
                if(dfs(x+dx[i], y+dy[i],index+1,visit)) return true;
            }
            visit[x][y] = false;
        }
        return false;
    }

    bool exist(VVC &board, string word) {
        this->board = board;
        this->word = word;
        n = board.size();
        m = board[0].size();
        VVB visit(n,vector<bool>(m,false));
        for(int i = 0 ; i < n; ++i ){
            for(int j = 0 ; j < m ;++ j){
                if(dfs(i,j,0,visit)) return true;
            }
        }
        return false;
    }
};

 

 

 

Leetcode Word Search,布布扣,bubuko.com

Leetcode Word Search

原文:http://www.cnblogs.com/xiongqiangcs/p/3826258.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!