zoukankan      html  css  js  c++  java
  • leetcode70word-search

    题目描述

    给出一个二维字符数组和一个单词,判断单词是否在数组中出现,
    单词由相邻单元格的字母连接而成,相邻单元指的是上下左右相邻。同一单元格的字母不能多次使用。
    例如:
    给出的字符数组=
    [↵  ["ABCE"],↵  ["SFCS"],↵  ["ADEE"]↵]
    单词 ="ABCCED", -> 返回 true,
    单词 ="SEE", ->返回 true,
    单词 ="ABCB", -> 返回 false.

    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", -> returnstrue,
    word ="SEE", -> returnstrue,

    class Solution {
    public:
        bool isOut(int r,int c,int rows,int cols){
            return c<0 || c>=cols || r<0 || r>=rows;
        }
        bool DFS(vector< vector< char >>&board,int r, int c,string &word,int start){
            if (start>=word.size())
                return true;
            if (isOut(r,c,board.size(),board[0].size() )|| word[start]!=board[r][c])
                return false;
            int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
            char tmp=board[r][c];
            board [r][c]='.';
            for (int i=0;i<4;++i){
                if (DFS(board,r+dx[i],c+dy[i],word,start+1))
                    return true;
            }
            board[r][c]=tmp;
            return false;
        }
        bool exist(vector<vector<char> > &board, string word) {
            int rows=board.size(),cols=board[0].size();
            for (int r=0;r<rows;++r)
                for (int c=0;c<cols;++c){
                    if (board[r][c]==word[0])
                        if (DFS(board,r,c,word,0))
                            return true;
                }
                return false;
            
        }
    };

  • 相关阅读:
    Zookeeper 系列(五)Curator API
    Zookeeper 系列(四)ZKClient API
    Zookeeper 系列(三)Zookeeper API
    Zookeeper 系列(二)安装配制
    [bzoj 2393] Cirno的完美算数教室 (容斥原理+dfs剪枝)
    [Sdoi2013] [bzoj 3198] spring (hash+容斥原理)
    [bzoj 1471] 不相交路径 (容斥原理)
    [bzoj 3701] Olympic Games (莫比乌斯反演)
    [bzoj 2693] jzptab & [bzoj 2154] Crash的数字表格 (莫比乌斯反演)
    [51Nod 1244]
  • 原文地址:https://www.cnblogs.com/hrnn/p/13413563.html
Copyright © 2011-2022 走看看