• 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;
        }
    };
    
  • 相关阅读:
    从技术演变的角度看互联网后台架构
    设计模式的六大原则
    Xinetd服务的安装与配置详解
    linux route详细解读
    Linux信号处理
    Go语言的成功也预示着Rust的成功【转】
    Nginx/LVS/HAProxy负载均衡软件的优缺点详解
    C#代码覆盖率实践-vsinstr和OpenCover
    MYSQL企业常用架构与调优经验分享
    StrongLoop
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6931193.html
Copyright © 2020-2023  润新知