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

LeetCode Word Search

时间:2014-12-04 08:48:28      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:leetcode   word search   

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:
    bool dfs(int depth,vector<vector<char> >&board,string word,int x,int y){
        if(depth==word.size())
        {
            return true;
        }
        else if(x>=board.size()||x<0)return false;
        else if(y>=board[0].size()||y<0)return false;
        else
        {
            if(board[x][y]==word[depth])
            {
                board[x][y]='.';
                if(dfs(depth+1,board,word,x+1,y))return true;
                if(dfs(depth+1,board,word,x,y+1))return true;
                if(dfs(depth+1,board,word,x-1,y))return true;
                if(dfs(depth+1,board,word,x,y-1))return true;
                board[x][y]=word[depth];
                return false;
            }
            else
                return false;
        }
    }
    bool exist(vector<vector<char> > &board, string word) {
        bool f=false;
        if(board.size()==0)return false;
        if(board[0].size()==0)return true;
        for(int i=0;i<board.size();++i)
            for(int j=0;j<board[0].size();++j)
            {
                if(dfs(0,board,word,i,j))
                    f=true;
            }
        //if(f==true)cout<<"true"<<endl;
        //else std::cout << "false" << std::endl;
        return f;
    }
};


LeetCode Word Search

标签:leetcode   word search   

原文地址:http://blog.csdn.net/wdkirchhoff/article/details/41708539

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