Leetcode Word Search

Leetcode Word Search 相关代码,本代码使用dfs(广度优先搜索)算法,以下给出代码示例,以及相关测试:

#include<vector>
#include<iostream>
#include<string>

using namespace std;

/*
 * We use the DFS algorithm complete this problem.
 */

class Solution {
public:
    bool exist(vector<vector<char> >& board, string word) {
        // Save the Row and Col to reduce the cost by invoke the vector::size()
        int Row = board.size();
        int Col = 0;
        if (Row > 0) {
            Col = board[0].size();
        }
        for (int i = 0; i < Row; i ++) {
            for (int j = 0; j < Col; j ++) {
                if (search(board, word, 0, i, j, Row, Col)) {
                    return true;
                }
            }
        }
        return false;
    }

    // use recursive and dfs to solve this problem
    bool search(vector<vector<char> >& board, string& word, int pos, int pos_x, \
            int pos_y, int Row, int Col) {
        if (word.length() == pos) {
            return true;
        } else {
            if (pos_x < 0 || pos_x >= Row || pos_y < 0 || pos_y >= Col \
                    || board[pos_x][pos_y] == ' ') {
                return false;
            }
            if (board[pos_x][pos_y] == word[pos]) {
                char temp = board[pos_x][pos_y];
                board[pos_x][pos_y] = ' ';
                bool re = search(board, word, pos + 1, pos_x + 1, pos_y, Row, Col) || \
                    search(board, word, pos + 1, pos_x - 1, pos_y, Row, Col) || \
                    search(board, word, pos + 1, pos_x, pos_y + 1, Row, Col) || \
                    search(board, word, pos + 1, pos_x, pos_y - 1, Row, Col);
               if (re) {
                  return true;
               } else {
                   board[pos_x][pos_y] = temp;
               }
            }
            return false;
        }
    }
};


int main(int argc, char* argv[]) {
    vector<vector<char> > test;
    vector<char> ele1(2, 'a');
    vector<char> ele2(2, 'b');
    test.push_back(ele1);
    test.push_back(ele2);
    Solution so;
    bool re = so.exist(test, "abba");
    cout<<"result: "<<re<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值