论坛首页 编程语言技术论坛

[Leetcode] Word Search

浏览 1220 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-09-21  

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.

 

 

同学们把leetcode刷了一遍又一遍~

 

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        int n = board.size();
        if (n == 0) return false;
        int m = board[0].size();
        set<pair<int,int> >s;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (check(board, word, i, j, 0, s) == true) return true;
            }
        }
        return false;
    }
    
    bool check(vector<vector<char> >&a, string& w, int x, int y, int cnt, set<pair<int,int> >&s) {
        if (cnt == w.size()) return true;
		if (x >= a.size() || x < 0 || y >= a[0].size() || y < 0) return false;
        if (s.count(make_pair(x,y)) > 0)return false;
        if (w[cnt] != a[x][y]) return false;
        s.insert(make_pair(x,y));
        int dx[] = {0,0,1,-1};
        int dy[] = {1,-1,0,0};
        for (int i = 0; i < 4; i++) {
            if (check(a, w, x+dx[i], y+dy[i], cnt+1, s) == true) return true;
        }
        s.erase(make_pair(x,y));
        return false;
    } 
};

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics