Leetcode之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 helper(vector<vector<char>>& board, string word, int i, int j) {

	int h = board.size();
	int w = board[0].size();
	if (board[i][j] == word[0]) {
		board[i][j] = '.';
		string s = word.substr(1);
		if (s.length() == 0)return true;
		if (i > 0 && helper(board, s, i - 1, j))return true;
		if (j > 0 && helper(board, s, i, j - 1))return true;
		if (i < h-1 && helper(board, s, i + 1, j))return true;
		if (j < w - 1 && helper(board, s, i, j + 1))return true;
		board[i][j] = word[0];
	}
	return false;
}
    bool exist(vector<vector<char>>& board, string word) {
        	int len = word.length();
	if (len == 0)return true;
	char first = word[0];
	for (int i = 0; i < board.size(); i++) {
		for (int j = 0; j < board[i].size(); j++) {
			if (board[i][j] == first) {
				if (helper(board, word, i, j))return true;
			}
		}
	}
	return false;
    }
};

想法:

需要考虑全面一些

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/89375309