首页 > 其他 > 详细

Word Search -- leetcode

时间:2015-04-14 13:02:53      阅读:104      评论: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.


基本思路:

1. 对棋盘每个点进行深度优搜索。

2. 传统Ascii码,只会用7bit,最高bit为0. 故可用此bit位,复用作访问标志位。



class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        if (board.empty() || board[0].empty()) return false;
        
        for (int i=0; i<board.size(); i++) {
            for (int j=0; j<board[0].size(); j++) {
                if (exist(board, word, 0, i, j))
                    return true;
            }
        }
        
        return false;
    }
    
    bool exist(vector<vector<char> >&board, const string &word, int index, int x, int y) {
        if (index == word.size()) return true;
        if (x<0 || y<0 || x==board.size() || y==board[0].size()) return false;
        if (board[x][y] != word[index]) return false;
        
        board[x][y] ^= 128;
        const bool existed = exist(board, word, index+1, x, y+1) ||
                             exist(board, word, index+1, x, y-1) ||
                             exist(board, word, index+1, x+1, y) ||
                             exist(board, word, index+1, x-1, y);
        board[x][y] ^= 128;
        
        return existed;
    }
};


Word Search -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/45039107

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!