[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 =[["ABCE"],["SFCS"],["ADEE"]]

word="ABCCED",->return true,

word="SEE",->return true,

word="ABCB",->return false.


思路:本人想到的解决思路是采用递归的方式,首先定义一个相同的二维数组,用于标记某位是否已经被查找。然后进行上下左右匹配,任何一个方向的能够完成查找即可返回true。返回true的条件是当前位置没有被标记&当前位置的字符等于字串的首字母&字串的长度为1

代码实现如下:

class Position{//保存位置信息
	int i;
	int j;
	public Position(int m,int n){
		i=m;
		j=n;
	}
}
public class Solution {
   public static boolean exist(char[][] board, String word) {
		boolean result=false;
		if(word==null||word.length()==0||board==null||board.length==0) return false;
		Position p;
		int m_size=board.length;
		int n_size=board[0].length;
		int[][] mark=new int[m_size][n_size];//保存标记
		
		char w=word.charAt(0);
		for(int m=0;m<m_size;m++){
			for(int n=0;n<n_size;n++){
				if(board[m][n]==w){
					
					p=new Position(m,n);
					result=getResult(mark,board,word,p);
					if(result)return result;
					
				}
			}
		}
		
		return result;
		
	}
	
	public static boolean getResult(int[][] mark,char[][] board,String word,Position p){
		int m=p.i;
		int n=p.j;		
		boolean result=false;
		if(n<0||m<0||n>=board[0].length||m>=board.length||mark[m][n]==1)return false;
		if(board[m][n]==word.charAt(0)){
			if(word.length()==1)return true;//如果长度为1,则返回true,跳出循环
			String word2=word.substring(1);
			mark[m][n]=1;
			result=getResult(mark,board,word2,new Position(m-1,n))||
				getResult(mark,board,word2,new Position(m+1,n))||
				getResult(mark,board,word2,new Position(m,n-1))||
				getResult(mark,board,word2,new Position(m,n+1));
			//left
		}
		if(!result) mark[m][n]=0;
		return result;		
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值