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;
        }
    };
    
  • 相关阅读:
    .net Thrift 之旅 (一) Windows 安装及 HelloWorld
    软件测试中的过度设计
    血型和测试
    功能点算法及在软件测试中的应用Part2
    尘归尘 土归土
    解读SAO文化中的Share
    使用C#开发winform程序的界面框架
    怎样才能说明软件测试工作做的好?
    功能点算法及在软件测试中的应用Part1
    软件测试的核心价值是什么?
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6931193.html
Copyright © 2011-2022 走看看