LeetCode 79. Word Search(单词查找)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/princexiexiaofeng/article/details/79645805

题目描述:

    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 .

分析:
    题意:给定一个二维字符数组,一个字符串。判断数组中是否能查找到该字符串。数组中字符连接方式为水平或者垂直。
    思路:这道题采用DFS搜索。我们假设字符数组board二维的大小分别为m、n,字符串word长度为len,我们用x,y表示当前已经搜索过的元素坐标,k表示已经查找到的字符串的长度。① 对于i∈0→m - 1,j∈0→n - 1,如果board[i][j]等于word[0],则i,j可以作为DFS搜索的起点;② 如果k等于len,则已经找到符合的字符串,返回true;③ 从(x, y)开始向四个方向搜索,更新坐标为(xx, yy),如果遇到board[xx][yy]等于word[k],则当前保持匹配,可以继续深入搜索。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
private: 
	bool ans;
	int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
	
	void DFS(vector<vector<char>>& board, string word, int m, int n, int len, int x, int y, int k){
		if(ans){
			return;
		}
		if(k == len){
			ans = true;
			return;
		}
		for(int i = 0; i <= 3; i++){
			int xx = x + dir[i][0];
			int yy = y + dir[i][1];
			if(xx >= 0 && xx <= m - 1 && yy >= 0 && yy <= n - 1 && board[xx][yy] == word[k]){
				board[xx][yy] = '.';
				DFS(board, word, m, n, len, xx, yy, k + 1);
				board[xx][yy] = word[k];
			}
		}
	}

public:
    bool exist(vector<vector<char>>& board, string word) {
        ans = false;
		if(board.empty()){
			return ans;
		}
		int len = word.length();
		int m = board.size(), n = board[0].size();
		if(len == 0 || m == 0 || n == 0){
			return ans;
		}
		for(int i = 0; i <= m - 1; i++){
			for(int j = 0; j <= n - 1; j++){
				if(board[i][j] == word[0]){
					board[i][j] = '.';
					DFS(board, word, m, n, len, i, j, 1);
					if(ans){
						return true;
					}
					board[i][j] = word[0];
				}
			}
		}
		return false;
    }
};

猜你喜欢

转载自blog.csdn.net/princexiexiaofeng/article/details/79645805