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.

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。代码如下,使用了回溯,如果不回溯的话可以直接选择传参也是可以通过的,但是运行效率慢了3倍。

#include<iostream>
#include<string>
#include<vector> 
using namespace std;
class Solution {
public:
	string w;
	int row,col,l;
    bool exist(vector<vector<char>>& board, string word) {
        if(board.size()==0)
        {
        	if(word=="")
        	return 1;
        	else
        	return 0;
		}
		w=word;
		row=board.size();
		col=board[0].size();
		l=word.length();
		for(int i=0;i<row;i++)
		{
			for(int j=0;j<col;j++)
			{
				if(board[i][j]==word[0])
				if(dfs(board,0,i,j))
				return true;
			}
		}
		return false;
    }
    bool dfs(vector<vector<char>>& board,int current,int r,int c)
    {
    	
    	if(l==current+1)
    	return true;
    	char s=board[r][c];
    	board[r][c]='0';
    	//cout<<r<<c<<endl;
    	if(r+1<row&&board[r+1][c]==w[current+1])
		{
			if(dfs(board,current+1,r+1,c))
			return true;
		}
		if(r-1>=0&&board[r-1][c]==w[current+1])
		{
			if(dfs(board,current+1,r-1,c))
			return true;
		}
		if(c-1>=0&&board[r][c-1]==w[current+1])
		{
			if(dfs(board,current+1,r,c-1))
			return true;
		}
		if(c+1<col&&board[r][c+1]==w[current+1])
		{
			if(dfs(board,current+1,r,c+1))
			return true;
		}
		board[r][c]=s;
		 return false;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值