zoukankan      html  css  js  c++  java
  • 79. Word Search (Array; DFS,Back-Track)

    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
    class Solution {
    public:
        bool exist(vector<vector<char> > &board, string word) {
            if(board.empty()) return false;
            vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
            bool result = false;
            for(int i = 0; i < board.size(); i++)
            {
                for(int j = 0; j < board[0].size(); j++)
                {
                     result = dfs(board,word,i,j,0,visited);
                     if(result) return true;
                     visited[i][j] = false; //回溯
                }
            }
            return false;
        }
    
        bool dfs(vector<vector<char> > &board, string word, int i, int j, int depth, vector<vector<bool>> &visited)
        {
            if(board[i][j] != word[depth]) return false;
            if(depth == word.length()-1) return true;
            visited[i][j] = true;
            if(j < board[0].size()-1 && !visited[i][j+1]){ //向右
                if(dfs(board,word, i, j+1, depth+1,visited)) return true;
                else visited[i][j+1] = false;  //回溯
            }
            if(j > 0 && !visited[i][j-1]) //向左
            {
                if(dfs(board,word, i, j-1, depth+1,visited)) return true;
                else visited[i][j-1] = false; //回溯
            }
            if(i < board.size()-1 && !visited[i+1][j]) //向下
            {
                if(dfs(board,word, i+1, j, depth+1,visited)) return true;
                else visited[i+1][j] = false; //回溯
            }
            if(i > 0  && !visited[i-1][j]) //向上
            {
                if(dfs(board, word, i-1, j, depth+1,visited)) return true;
                else visited[i-1][j] = false;  //回溯
            }
            return false;
        }
    };
     
     
  • 相关阅读:
    C# 16进制与字符串、字节数组之间的转换
    多文件上传方法
    超链接如何下载文件txt,word,excel等等
    asp.net不同类型文件读取处理
    .net二进制图片存储与读取的常见方法
    c#事务
    C#中的null和数据库中的null的区别
    Asp.net中Response.Charset 与Response.ContentEncoding区别
    导出到word
    js导出word
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854674.html
Copyright © 2011-2022 走看看