zoukankan      html  css  js  c++  java
  • Leetcode: 79. Word Search

    Description

    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.

    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 exist(vector<vector<char>>& board, string word) {
            int m = board.size();
            if(m == 0 || word.size() == 0) return false;
            int n = board[0].size();
            
            for(int i = 0; i < m; ++i){
                for(int j = 0; j < n; ++j){
                    if(board[i][j] == word[0]){
                        vector<vector<bool>> flag(m, vector<bool>(n, false));
                        if(judge(board, i, j, m, n, word, 0, flag))
                            return true;
                    }
                }
            }
            
            return false;
        }
        
        bool judge(vector<vector<char>>& board, int i, int j, int m, int n,
            string& word, int k, vector<vector<bool>>& flag){
            
            if(i < 0 || j < 0 || i == m || j == n 
                || flag[i][j] || board[i][j] != word[k])
                return false;
            
            flag[i][j] = true;
            if(k == word.size() - 1) return true;
            
            bool res = judge(board, i + 1, j, m, n, word, k + 1, flag)
                 || judge(board, i - 1, j, m, n, word, k + 1, flag)
                 || judge(board, i, j + 1, m, n, word, k + 1, flag)
                 || judge(board, i, j - 1, m, n, word, k + 1, flag);
                 
            flag[i][j] = false;
            return res;
        }
    };
    
  • 相关阅读:
    数据库之完整性约束
    数据库之数据类型
    数据库之表操作,数据操作
    mysql数据库之基本操作和存储引擎
    MySQL数据库之安装
    并发编程之socketserver模块
    python并发编程之IO模型
    [BZOJ 3207] 花神的嘲讽计划Ⅰ【Hash + 可持久化线段树】
    [BZOJ 1046] [HAOI2007] 上升序列 【DP】
    [BZOJ 1816] [Cqoi2010] 扑克牌 【二分答案】
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6931193.html
Copyright © 2011-2022 走看看