【LeetCode】79. Word Search

题目:

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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

 

描述:

给出一个二维数组和一个目标单词,判断该单词是否在数组中存在,其中只能使用水平或垂直方向相邻的字符,并且每个字符只能使用一次

 

分析:

暴力搜索就行,种子填充法

 

代码:

class Solution {
public:
	bool exist(vector>& board, string word) {
		
		for (int i = 0; i < board.size(); ++ i) {
			for (int j = 0; j < board[0].size(); ++ j) {
				if (board[i][j] != word[0]) {
					continue;
				}
				if (match(board, word, 0, i, j)) {
					return true;
				}
			}
		}
		return false;
	}
	bool match(vector>& board, const string &word, int index, int row, int column) {
		
		int n = board.size(), m = board[0].size();
		if (index == word.size()) {
			return true;
		}
		if (row < 0 || row >= n || column < 0 || column >= m || board[row][column] != word[index]) {
			return false;
		}
		int temp = board[row][column];
		board[row][column] = 0;
		
		for (int i = -1; i <= 1; ++ i) {
			for (int j = -1; j <= 1; ++ j) {
				if (abs(i) == abs(j)) {
					continue;
				}
				if (match(board, word, index + 1, row + i, column + j)) {
					return true;
				}
			}
		}
		if (!board[row][column]) {
			board[row][column] = temp;
		}
		return false;
	}
};

 

你可能感兴趣的:(LeetCode)