---
title: "[Leetcode] Word Search "
author: "cozilla"
date: "2013-09-21T23:21:41Z"
tags: []
categories: ["非技术"]
slug: "leetcode-word-search"
draft: false
lastmod: "2013-09-21T23:21:41Z"
id: 1944562
url: "https://cozilla.iteye.com/blog/1944562"
---

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"`, -&gt; returns `true`,  
**word** = `"SEE"`, -&gt; returns `true`,  
**word** = `"ABCB"`, -&gt; 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;
    } 
};
```