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

[leetcode]Word Search

时间:2015-04-13 14:46:16      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:dfs   leetcode   

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)找到开始的入口,这里就是找到和值word[0]一样的位置
2)开始递归查找,word[1],word[2]….word[word.size()-1],和解迷宫题一样,这里是要求相邻的格子,所以上下左右四个方向寻找合适的解。
3)如果cur=word.size(),代表已经找到了这个单词的所有字符,返回成功。算法结束。

class Solution {
public:
    bool visited[100][100];
    int  step[4][2];

    void dfs(int x,int y,int cur,int len,string &word,vector<vector<char> > &board,bool &flag){
        if(flag)  return;
        if(cur == len) {
            flag = true;
            return;
        }
        for(int i=0;i<4;i++){
            int tx = x + step[i][0];
            int ty = y + step[i][1];
            if(tx >=0 && tx < board.size() && ty >= 0 && ty < board[0].size() && (visited[tx][ty] == false) && board[tx][ty] == word[cur]){
                visited[tx][ty] = true;
                dfs(tx,ty,cur+1,len,word,board,flag);
                visited[tx][ty] = false;
            }
        }

    }
    void init(){
        memset(visited,false,sizeof(visited));
        step[0][0] = 1;
        step[0][1] = 0;
        step[1][0] = -1;
        step[1][1] = 0;
        step[2][0] = 0;
        step[2][1] = 1;
        step[3][0] = 0;
        step[3][1] = -1;
    }

    bool exist(vector<vector<char> > &board, string word) {
        int i,j;
        if (word.size() == 0)  return true;
        init();
        for(i=0; i<board.size();i++){
            for(j=0;j<board[0].size();j++){
                if(board[i][j]==word[0]){
                    bool flag = false;
                    visited[i][j] = true;
                    dfs(i,j,1,word.size(),word,board,flag);
                    if(flag) return true;
                    visited[i][j] = false;
                }
            }    
        }
        return false;
    }
};

[leetcode]Word Search

标签:dfs   leetcode   

原文地址:http://blog.csdn.net/iboxty/article/details/45024189

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