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.

For example,
Given board =
[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.


解题报告:

开始时使用bfs,超时,后来改为dfs就通过了

#include<iostream>
#include<vector>
#include<set>
using namespace std;

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
	
	if(word.length()==0)
		return true;
	
	if(board.size()==0)
		return false;
	
	int m = board.size();
	int n = board[0].size();	
	if( word.length() > m*n )
		return false;
	
	for(int i=0;i<m;++i){
		for(int j=0;j<n;++j){
			if(board[i][j]==word[0]){
				Pos pos;
				pos.i=i;
				pos.j=j;
				vector<Pos> vpos;
				vpos.push_back(pos);
				if(dfs(board,word,1,i,j,vpos))
					return true;
			}	
		}
	}
	return false;
    }

    struct Pos{
    	int i,j;
    };

    bool dfs(vector<vector<char> > &board,string word,int word_index,int i,int j,vector<Pos> &vpos){
	
	if(word_index>=word.length())
		return true;

    int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
	int m = board.size();
	int n = board[0].size();	

	for(int k=0;k<4;++k){
		int ni = i + dir[k][0];
		int nj = j + dir[k][1];
		if(ni>=0&&ni<m&&nj>=0&&nj<n&&board[ni][nj]==word[word_index]){
			//not appare
			bool find = false;
			for(int i0=0;i0<vpos.size();++i0){
				if(ni==vpos[i0].i&&nj==vpos[i0].j){
					find=true;
					break;
				}
			}
			if(find)
				continue;

			Pos pos;
			pos.i=ni;
			pos.j=nj;
			vpos.push_back(pos);
			if(dfs(board,word,word_index+1,ni,nj,vpos))
				return true;	
			vpos.pop_back();
		}
	}
	return false;
    }
};     

int main(){

	vector<vector<char> > board;
	
	vector<char> vchar0;
	vchar0.push_back('A');
	vchar0.push_back('B');
	vchar0.push_back('C');
	vchar0.push_back('E');
	board.push_back(vchar0);

	vector<char> vchar1;
	vchar1.push_back('S');
	vchar1.push_back('F');
	vchar1.push_back('C');
	vchar1.push_back('S');
	board.push_back(vchar1);

	vector<char> vchar2;
	vchar2.push_back('A');
	vchar2.push_back('D');
	vchar2.push_back('E');
	vchar2.push_back('E');
	board.push_back(vchar2);

	Solution s;
	cout<<s.exist(board,"ABCE")<<endl;
	cout<<s.exist(board,"SEE")<<endl;
	cout<<s.exist(board,"ABCB")<<endl;
	cout<<s.exist(board,"A")<<endl;
	cout<<s.exist(board,"DA")<<endl;
	cout<<s.exist(board,"M")<<endl;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值