LeetCode —— Word Search

链接:http://leetcode.com/onlinejudge#question_79

原题:

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 .

思路:dfs搜索,按四个方向走,不断回溯

const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

代码:

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (word.size()==0)
            return true;
        if (board.size()==0)
            return false;
        int rows = board.size();
        int cols = board[0].size();
        vector<vector<bool> > used;
        for (int i=0; i<rows; i++)
            used.push_back(vector<bool>(cols));
        for (int i=0; i<rows; i++) {
            for (int j=0; j<cols; j++) {
                if (word[0]==board[i][j]) {
                    used[i][j] = true;
                    if (dfs(board, used, word, 1, i, j))
                        return true;
                    used[i][j] = false;
                }
            }
        }
        return false;
    }
    
private:
    static const int dir[4][2];
    
    bool dfs(const vector<vector<char> > &board, vector<vector<bool> > &used, 
        const string &word, int n, int x, int y) {
        
        if (n==word.size())
            return true;
        int rows = board.size();
        int cols = board[0].size();
        for (int i=0; i<4; i++) {
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];
            if (nx>=0 && nx<rows && ny>=0 && ny<cols) {
                if (!used[nx][ny] && word[n]==board[nx][ny]) {
                    used[nx][ny] = true;
                    if (dfs(board, used, word, n+1, nx, ny))
                        return true;
                    used[nx][ny] = false;
                }
            }
        }
        return false;
    }
};

const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值