zoukankan      html  css  js  c++  java
  • Java for LeetCode 079 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.

    解题思路:

    开一个数组用于保存数据是否被访问过,使用DFS即可,JAVA实现如下:

    static public boolean exist(char[][] board, String word) {
    		if (board.length == 0 || board[0].length == 0 || word.length() == 0)
    			return false;
    		boolean[][] isUsed=new boolean[board.length][board[0].length]; 
    		for (int i = 0; i < board.length; i++)
    			for (int j = 0; j < board[0].length; j++)
    				if (board[i][j] == word.charAt(0)){
    					isUsed[i][j]=true;
    					if(dfs(board,word,i,j,0,isUsed))
    						return true;
    					isUsed[i][j]=false;
    				}
    		return false;
    	}
    	public static boolean dfs(char[][] board,String word,int i,int j,int depth,boolean[][] isUsed){
    		if(depth==word.length()-1)
    			return true;
    		if(i>=1&&board[i-1][j]==word.charAt(depth+1)&&!isUsed[i-1][j]){
    			isUsed[i-1][j]=true;
    			if(dfs(board,word,i-1,j,depth+1,isUsed))
    				return true;
    			isUsed[i-1][j]=false;
    		}
    		if(i<=board.length-2&&board[i+1][j]==word.charAt(depth+1)&&!isUsed[i+1][j]){
    			isUsed[i+1][j]=true;
    			if(dfs(board,word,i+1,j,depth+1,isUsed))
    				return true;
    			isUsed[i+1][j]=false;
    			}
    		if(j>=1&&board[i][j-1]==word.charAt(depth+1)&&!isUsed[i][j-1]&&!isUsed[i][j-1]){
    			isUsed[i][j-1]=true;
    			if(dfs(board,word,i,j-1,depth+1,isUsed))
    				return true;
    			isUsed[i][j-1]=false;
    		}
    		if(j<=board[0].length-2&&board[i][j+1]==word.charAt(depth+1)&&!isUsed[i][j+1]){
    			isUsed[i][j+1]=true;
    			if(dfs(board,word,i,j+1,depth+1,isUsed))
    				return true;	
    			isUsed[i][j+1]=false;
    		}
    		return false;
    	}
    
  • 相关阅读:
    C#中判断是否为数值
    html中网页自动刷新设置
    html中多行文本及文件提交
    商品库存秒杀方案总结
    记一次asp.net core 线上崩溃解决总结
    Eova 怎么放在 Docker中,使用阿里云流水线构建Eova!!
    阿里云 asp.net core nginx 单机部署
    Tidb go mac 上开发环境搭建
    jexus+.netcore+identityserver4 部署支持ssl(https)
    使用mha 构建mysql高可用碰到几个问题
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4513340.html
Copyright © 2011-2022 走看看