zoukankan      html  css  js  c++  java
  • leetcode第一刷_Word Search

    这道题之前一直没敢做,没想到前天用递归一遍过了。

    当时为什么想着用递归,而不是dp呢。由于我想到达某个位置的情况有非常多,即使从当前位置開始的搜索是已知的,但之前的状态是如何的也无从得知啊,实话实说,我是不会用dp解这个。。

    递归的思路就好说多了,从当前点開始。有上下左右四个位置能够探測,假设探測成功的话,要把当前的位置用其它符号标记出来,以免反复訪问。实际上就是DFS嘛。仅仅只是入口多一些。

    须要注意的一点是,每一个点都能够作为起点。所以这个要穷举一下。否则会漏掉情况的。

    当然有一种情况走通就能够返回了。剪枝之。

    代码又臭又长,只是work:

    class Solution {
    public:
        int row, column;
        bool doexist(vector<vector<char> > &board, string &word, int len, int i, int j){
            if(len == word.length())    return true;
            bool res;
            if(i>0&&board[i-1][j] == word[len]){
                board[i-1][j] = '.';
                res = doexist(board, word, len+1, i-1, j);
                if(res) return true;
                else    board[i-1][j] = word[len];
            }
            if(i<row-1&&board[i+1][j] == word[len]){
                board[i+1][j] = '.';
                res = doexist(board, word, len+1, i+1, j);
                if(res) return true;
                else    board[i+1][j] = word[len];
            }
            if(j>0&&board[i][j-1] == word[len]){
                board[i][j-1] = '.';
                res = doexist(board, word, len+1, i, j-1);
                if(res) return true;
                else    board[i][j-1] = word[len];
            }
            if(j<column-1&&board[i][j+1] == word[len]){
                board[i][j+1] = '.';
                res = doexist(board, word, len+1, i, j+1);
                if(res) return true;
                else    board[i][j+1] = word[len];
            }
            return false;
        }
        bool exist(vector<vector<char> > &board, string word) {
            row = board.size();
            if(row == 0)    return false;
            column = board[0].size();
            char c;
            for(int i=0;i<row;i++){
                for(int j=0;j<column;j++){
                    if(board[i][j] == word[0]){
                        board[i][j] = '.';
                        if(doexist(board, word, 1, i, j))
                            return true;
                        board[i][j] = word[0];
                    }
                }
            }
            return false;
        }
    };


  • 相关阅读:
    20160220.CCPP体系详解(0030天)
    20160219.CCPP体系详解(0029天)
    20160217.CCPP体系详解(0027天)
    Discuz 如何开启 memcache
    20160216.CCPP体系详解(0026天)
    20160215.CCPP体系详解(0025天)
    Linux之父:诺基亚更应选择 Android 平台
    Linux 之父 Linus 的 8 个趣闻轶事
    Linux 中识别 USB 设备名字的 4 种方法
    码农们加班是“心甘情愿”吗?都是被“逼”的
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7242168.html
Copyright © 2011-2022 走看看