zoukankan      html  css  js  c++  java
  • [leetcode-79-Word Search]

    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 =
    [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
    ]
    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    思路:

    深度优先遍历。

    bool dfs(vector< vector< char> >& board, string word,int row ,int col ,int start,int m,int n,int length)
    {
        char curChar = board[row][col];
        bool res = false;
    
        if(curChar != word[start]) return false;
        if(start == length - 1) return true;
    
        board[row][col] = '*';
        if(row>0) res = dfs(board,word,row-1,col,start+1,m,n,length);
        if(!res && row < m-1) res = dfs(board,word,row+1,col,start+1,m,n,length);
        if(!res && col>0) res = dfs(board,word,row,col-1,start+1,m,n,length);
        if(!res && col<n-1) res = dfs(board,word,row,col+1,start+1,m,n,length);
        board[row][col] = curChar;
    
        return res;
    }
    bool exist(vector< vector< char> >& board, string word)
    {
        int m = board.size() , n = board[0].size(), length = word.size();
    
        if( m && n && length)
        {
            for(int i = 0;i < m;i++)
            {
                for(int j =0;j<n;j++)
                {
                    if(dfs(board,word,i,j,0,m,n,length))
                        return true;
                }
            }
        }
        return false;
    }
  • 相关阅读:
    用python写一个北京市的个税计算器
    排序算法(冒泡、选择)-python代码展示
    封装系统内置功能的函数(字符串)
    福彩习题
    打印等腰三角形
    1.冒泡排序法
    腾讯云:搭建 Node.js 环境
    python开发环境搭建
    基于 Ubuntu 搭建 FTP 文件服务
    TensorFlow — 相关 API
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6751970.html
Copyright © 2011-2022 走看看