首页 > 其他 > 详细

LeetCode Word Search

时间:2014-12-04 08:46:57      阅读:241      评论: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:
    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

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

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