Lintcode_123 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.

Example

Given board =

[
  "ABCE",
  "SFCS",
  "ADEE"
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

看似简单,其实在写的时候遇到了诸多问题:

如果用bfs来解决,必须每次都搞一个新的矩阵乎哟这vector来记录当前路径上锁浏览过的点, 不能使用引用类型,否则出错;

虽然能计算,但是内存不够, 爆了~~

只能使用DFS来做, 随意必须使用引用类型来节约内存:

如果当前点符合条件, 则计算相邻的点,注意在进行下一侧迭代的时候,必须将当前的点置为#,然后DFS四个相邻点,注意,在返回

此次迭代前,必须把当前点还原,否则会出错影响其他点的DFS;

class Solution {
public:
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    bool exist(vector<vector<char> > &board, string word) {
        // write your code here
        if (word.size() == 0 || board.empty()) {
            return false;
        }
        
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[0].size(); j++){
                if (DFS(board, i, j, 0, word))
                    return true;
            }
        }
        return false;
        
    }
    bool DFS(vector<vector<char> > &board, int i, int j, int len, string word) {
        if (0 <= i && i < board.size() && 0 <= j && j < board[0].size()) {
           if (len == (int)word.size() - 1 && board[i][j] == word[len]) {
                   return true;
           }
           if (board[i][j] != word[len]) {
               return false;
           }
           //cout<<i<<" "<<j<<" "<<board[i][j]<<endl;
           char c = board[i][j];
           board[i][j] = '#';
           bool res = DFS(board, i - 1, j, len + 1,word) ||
                      DFS(board, i + 1, j, len + 1,word) ||
                      DFS(board, i, j - 1, len + 1,word) ||
                      DFS(board, i, j + 1, len + 1,word);
           board[i][j] = c;
           return res;
        } else {
            return false;
        }
        
    }
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值