码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Word Search

时间:2015-07-30 14:59:16      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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.

For example,
Given board =

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

解题思路:

回溯法。用一个二维数组标记是否已经访问,然后朝上下左右四个方向进行扩展即可。

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int len = word.length();
        if(len==0){
            return true;
        }
        int m = board.size();
        if(m==0){
            return false;
        }
        int n = board[0].size();
        if(n==0){
            return false;
        }
        vector<vector<bool>> flag(m, vector<bool>(n, false));
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(helper(board, flag, i, j, 0, word)){
                    return true;
                }
            }
        }
        return false;
    }
    
    bool helper(vector<vector<char>>& board, vector<vector<bool>>& flag, int i, int j, int index, string& word){
        if(index>=word.length()){
            return true;
        }
        int m = board.size();
        int n = board[0].size();
        if(i<0 || i>=m || j<0 || j>=n || flag[i][j] || board[i][j]!=word[index]){
            return false;
        }
        flag[i][j] = true;
        bool result = helper(board, flag, i+1, j, index + 1, word) ||
                      helper(board, flag, i, j+1, index + 1, word) ||
                      helper(board, flag, i-1, j, index + 1, word) ||
                      helper(board, flag, i, j-1, index + 1, word);
        flag[i][j] = false;
        return result;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Word Search

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/47148955

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!