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

【Word Search】cpp

时间:2015-05-29 13:39:20      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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)
        {
            vector<vector<bool> > visited;
            for ( size_t i = 0; i < board.size(); ++i )
            {
                vector<bool> tmp(board[i].size(),false);
                visited.push_back(tmp);
            }
            for ( int i = 0; i < board.size(); ++i )
            {
                for ( int j = 0; j < board[i].size(); ++j )
                {
                    if (Solution::dfs(board, visited, i, j, word, 0)) return true;
                }
            }
            return Solution::dfs(board, visited, 0, 0, word, 0);
        }
        static bool dfs( 
            vector<vector<char> >& board,
            vector<vector<bool> >& visited,
            int i,
            int j,
            string& word,
            int curr )
        {
            if ( curr==word.size() ) return true;
            if ( i<0 || i==board.size() || j<0 || j==board[i].size() ) return false;
            if ( visited[i][j] ) return false;
            if ( board[i][j]!=word[curr] ) return false;
            if ( board[i][j]==word[curr] ) 
            {
                visited[i][j] = true;
                if ( Solution::dfs(board, visited, i, j+1, word, curr+1)) return true;
                if ( Solution::dfs(board, visited, i+1, j, word, curr+1)) return true;
                if ( Solution::dfs(board, visited, i, j-1, word, curr+1)) return true;
                if ( Solution::dfs(board, visited, i-1, j, word, curr+1)) return true;
            }
            visited[i][j] = false;
            return false;
        }
};

tips:

好好领悟一下dfs吧。。。

1. 这道题在主程序中有一个循环,如果一旦发现word的起点,就从这个位置开始dfs,看能否返回结果。

2. dfs的过程跟模板一样。

shit

【Word Search】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4538024.html

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