zoukankan      html  css  js  c++  java
  • Word Search

    -----QUESTION-----

    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 =

     [ ["ABCE"], ["SFCS"], ["ADEE"] ]
    word "ABCCED", -> returns true,
    word "SEE", -> returns true,
    word "ABCB", -> returns false.

    -----SOLUTION-----

    class Solution {
    public:
        bool exist(vector<vector<char> > &board, string word) {
            if(board.empty()) return false;
            vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
            bool result = false;
            for(int i = 0; i < board.size(); i++)
            {
                for(int j = 0; j < board[0].size(); j++)
                {
                     result = dfs(board,word,i,j,0,visited);
                     if(result) return true;
                     visited[i][j] = false;
                }
            }
            return false;
        }
        bool dfs(vector<vector<char> > &board, string word, int i, int j, int depth, vector<vector<bool>> &visited)
        {
            if(board[i][j] != word[depth]) return false;
            if(depth == word.length()-1) return true;
            visited[i][j] = true;
            if(j < board[0].size()-1 && !visited[i][j+1]){
                if(dfs(board,word, i, j+1, depth+1,visited)) return true;
                else visited[i][j+1] = false;
            }
            if(j > 0 && !visited[i][j-1])
            {
                if(dfs(board,word, i, j-1, depth+1,visited)) return true;
                else visited[i][j-1] = false;
            }
            if(i < board.size()-1 && !visited[i+1][j]) 
            {
                if(dfs(board,word, i+1, j, depth+1,visited)) return true;
                else visited[i+1][j] = false;
            }
            if(i > 0  && !visited[i-1][j]) 
            {
                if(dfs(board, word, i-1, j, depth+1,visited)) return true;
                else visited[i-1][j] = false;
            }
            return false;
        }
    };


  • 相关阅读:
    数据结构-二叉搜索树
    多任务处理方式之一:多进程
    TCP并发服务器
    REST是什么?RESTFul又是什么?这二者的关系是怎样的?
    Python中的深浅拷贝的区别
    查找算法之 '二分法查找'
    排序算法之 '快速排序'
    CCS
    CCS
    CCS
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5068918.html
Copyright © 2011-2022 走看看