前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 79 Word Search

Leetcode 79 Word Search

作者头像
triplebee
发布2018-01-12 15:01:43
5520
发布2018-01-12 15:01:43
举报

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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,

word = "SEE", -> returns true,

word = "ABCB", -> returns false.

在矩阵中找单词。

又是一个深搜,代码不够精简,写死了。

class Solution {
public:
    bool dfs(vector<vector<char>>& board, string word,int x,int y,vector<vector<bool>>& vis)
    {
        if(word.empty()) return true;
        if(x+1<board.size() && word[0]==board[x+1][y] && !vis[x+1][y])
        {
            vis[x+1][y]=true;
            if(dfs(board,word.substr(1,word.size()-1),x+1,y,vis)) return true;
            vis[x+1][y]=false;
        }
        if(x-1>=0 && word[0]==board[x-1][y] && !vis[x-1][y]) 
        {
            vis[x-1][y]=true;
            if(dfs(board,word.substr(1,word.size()-1),x-1,y,vis)) return true;
            vis[x-1][y]=false;
        }
        if(y+1<board[0].size() && word[0]==board[x][y+1] && !vis[x][y+1]) 
        {
            vis[x][y+1]=true;
            if(dfs(board,word.substr(1,word.size()-1),x,y+1,vis)) return true;
            vis[x][y+1]=false;
        }
        if(y-1>=0 && word[0]==board[x][y-1] && !vis[x][y-1]) 
        {
            vis[x][y-1]=true;
            if(dfs(board,word.substr(1,word.size()-1),x,y-1,vis)) return true;
            vis[x][y-1]=false;
        }
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        if(word.empty()) return true;
        vector<bool> temp(board[0].size(),false);
        vector<vector<bool>> vis(board.size(),temp);
        for(int i=0;i<board.size();i++)
            for(int j=0;j<board[0].size();j++)
                if(word[0]==board[i][j])
                {
                    vis[i][j]=true;
                    if(dfs(board,word.substr(1,word.size()-1),i,j,vis)) return true;
                    vis[i][j]=false;
                }
        
        return false;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档