leetcode 79 单词搜索 / word search

题目描述:

leetcode 79 单词搜索 / word search_第1张图片

解题思路:搜索题,每个点分上下左右四个方向搜索,对每个点都跑一次,代码如下:

class Solution {
	public:
		bool exist(vector>& board, string word) {
			if(board.empty()) return false;
			int m = board.size();
			int n = board[0].size();
			vector> visit(m,vector(n,false));
			bool res = false;
			for(int i = 0 ;i < m ;i++){
				for(int j = 0 ;j < n;j++){
					res = dfsSearch(board,word,0,i,j,visit);
					if(res == true){
						return true;
					}
				}
			}
			return false;
		}
	private:
		bool dfsSearch(vector>& board,string& word,int cnt,int p,int q,vector>& visit){
			if(cnt == word.size()){   // 放最前面,不然会越界
				return true;
			}
			if(p < 0 || p >= board.size() || q < 0 || q >= board[0].size()){
				return false;
			}
			if(visit[p][q] == true || board[p][q] != word[cnt]){
				return false;
			}
			visit[p][q] = true;
		    if(dfsSearch(board,word,cnt + 1, p,q + 1,visit) || dfsSearch(board,word,cnt + 1, p + 1,q,visit) || dfsSearch(board,word,cnt + 1, p - 1,q,visit) || dfsSearch(board,word,cnt + 1, p,q - 1,visit)){
			return true;
		    }
		    visit[p][q] = false;
			return false;
		}
	};

你可能感兴趣的:(刷题)