leetcode Word Search

题目连接

https://leetcode.com/problems/word-search/  

Word Search

Description

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 =


[‘A’,’B’,’C’,’E’], 
[‘S’,’F’,’C’,’S’], 
[‘A’,’D’,’E’,’E’] 

word = “ABCCED”, -> returns true, 
word = “SEE”, -> returns true, 
word = “ABCB”, -> returns false.

const int dx[] = { 0, 0, -1, 1 }, dy[] = { -1, 1, 0, 0 };
class Solution {
public:
	int n, H, W;
	bool exist(vector<vector<char>>& board, string word) {
		n = word.length();
		H = board.size(), W = board[0].size();
		queue<pair<int, int>>q;
		for (int i = 0; i < H; i++) {
			for (int j = 0; j < W; j++) {
				if (word[0] == board[i][j]) {
					vector<vector<bool>> vis(H, vector<bool>(W));
					vis[i][j] = true;
					if (dfs(i, j, vis, board, word, 1)) return true;
				}
			}
		}
		return false;
	}
	bool dfs(int x, int y, vector<vector<bool>>& vis, vector<vector<char>>& board, string word, int cur) {
		if (cur == n) return true;
		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i], ny = y + dy[i];
			if (nx < 0 || nx >= H || ny <0 || ny >= W) continue;
			if (board[nx][ny] == word[cur] && !vis[nx][ny]) {
				vis[nx][ny] = true;
				if (dfs(nx, ny, vis, board, word, cur + 1)) return true;
				vis[nx][ny] = false;
			}
		}
		return false;
	}
};
posted @ 2015-12-09 20:37  GadyPu  阅读(184)  评论(0编辑  收藏  举报