zoukankan      html  css  js  c++  java
  • leetcode--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.

    public class Solution {
        /**
    	 * dfs algorithm implementation
    	 * @param board -char array
    	 * @param word -string to be searched
    	 * @return true if word is contained in board, false, otherwise
    	 * @author Averill Zheng
    	 * @version 2014-07-01
    	 * @since JDK 1.7
    	 */
    	public boolean exist(char[][] board, String word) {
    		int row = board.length, len = word.length();
    		if(row > 0 && len > 0){
    			int column = board[0].length;			
    			boolean[][] alreadyChecked = new boolean[row][column];
    			//dfs search for each board[i][j]
    			for(int i = 0; i < row; ++i){
    				for(int j = 0; j < column; ++j) {
    					if(dfs(board, i, j, alreadyChecked, word, 0))
    						return true;
    				}
    			}
    		}
    		return false;
    	}
    		
    	private boolean dfs(char[][] board, int i, int j, boolean[][] alreadyChecked, String word, int count) {
    		//ending condition of dfs
    		if(alreadyChecked[i][j] || board[i][j] != word.charAt(count))
    			return false;
    		
    		if(count == word.length() - 1)
    			return true;
    		//set current coordinates checked	
    		alreadyChecked[i][j] = true;
    		
    		//dfs implementations
    		if(i - 1 >= 0 && dfs(board, i - 1, j, alreadyChecked, word, count + 1))
    			return true; 
    		if(i + 1 < board.length && dfs(board, i + 1, j, alreadyChecked, word, count + 1))
    			return true;
    		if(j - 1 >= 0 && dfs(board, i, j - 1, alreadyChecked, word, count + 1))
    			return true;
    		if(j + 1 <board[0].length && dfs(board, i, j + 1, alreadyChecked, word, count + 1))
    			return true;
    		
    		//if the dfs find the string, the process is terminated,
    		//otherwise, we reset the coordinates (i,j) to unchecked for the other dfs searchs
    		alreadyChecked[i][j] = false;
    		return false;
        }
    }
    

      

  • 相关阅读:
    BZOJ4403: 序列统计【lucas定理+组合数学】
    BZOJ4767: 两双手【组合数学+容斥原理】
    BZOJ5340: [Ctsc2018]假面【概率+期望】【思维】
    BZOJ4710: [Jsoi2011]分特产【组合数学+容斥】
    BZOJ5091: [Lydsy1711月赛]摘苹果【期望DP】
    BZOJ3473: 字符串【后缀数组+思维】
    BZOJ3879: SvT【后缀数组+单调栈】
    BZOJ1369/BZOJ2865 【后缀数组+线段树】
    BZOJ3230: 相似子串【后缀数组】
    BZOJ4310: 跳蚤 【后缀数组+二分】
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3821673.html
Copyright © 2011-2022 走看看