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;
        }
    };
    
  • 相关阅读:
    guzzle 中间件原理
    K8S-K8S 环境搭建
    K8S-k8s 理念知识
    云计算的概念
    Linux-DHCP 交互的过程
    linux-怎么踢出系统当前已连接的用户
    linux-Centos 搭建http yum源
    linux-硬链接与软连接
    linux-centos网络配置bond
    linux-dd 一个测试文件
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6931193.html
Copyright © 2011-2022 走看看