【leetcode】79.(Medium)Word Search

解题思路:
回溯


提交代码:

class Solution {
    public boolean exist(char[][] board, String word) {
    	if(board.length==0&&board[0].length==0)	return false;
    	if(word.length()>board.length*board[0].length)	return false;
    	
    	boolean[][] map=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(word.charAt(0)!=board[i][j])
    				continue;
    			map[i][j]=true;
    			if(isExist(i,j,1,word,board,map))	return true;
    			map[i][j]=false;
    		}
    	}
    	return false;
    }
    
    public boolean isExist(int row,int column,int p,
    		String word,char[][] board,boolean[][] map) {
    	if(row<0||row>=board.length||column<0||column>=board[0].length)
    		return false;
    	if(p==word.length())	return true;
    	
    	//check up
    	if(row>0) {
    		if(map[row-1][column]==false) {
    			if(board[row-1][column]==word.charAt(p)) {
    				map[row-1][column]=true;
    				if(isExist(row-1,column,p+1,word,board,map))
    					return true;
    				map[row-1][column]=false;
    			}
    		}
    	}
    	
    	//check down
    	if(row<board.length-1) {
    		if(map[row+1][column]==false) {
    			if(board[row+1][column]==word.charAt(p)) {
    				map[row+1][column]=true;
    				if(isExist(row+1,column,p+1,word,board,map))
    					return true;
    				map[row+1][column]=false;
    			}
    		}
    	}
    	
    	//check left
    	if(column>0) {
    		if(map[row][column-1]==false) {
    			if(board[row][column-1]==word.charAt(p)) {
    				map[row][column-1]=true;
    				if(isExist(row,column-1,p+1,word,board,map))
    					return true;
    				map[row][column-1]=false;
    			}
    		}
    	}
    	
    	//check right
    	if(column<board[0].length-1) {
    		if(map[row][column+1]==false) {
    			if(board[row][column+1]==word.charAt(p)) {
    				map[row][column+1]=true;
    				if(isExist(row,column+1,p+1,word,board,map))
    					return true;
    				map[row][column+1]=false;
    			}
    		}
    	}
    	
    	return false;
    }
    
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/84387945