Why time limited


  • 0
    H
    public class Solution {
    boolean r = false;
    public boolean exist(char[][] board, String word) {
        int y = board.length;
        int x = board[0].length;
        if(y == 0 ) return false;
        char firstchar = word.charAt(0);
        for(int i = 0; i < y ; i++)
        	for(int j = 0; j < x; j++) {
        		if(board[i][j] == firstchar) {
        			find(i,j,word,board,null,0);
        			if(r == true) return true;
        		}
        	}
        return false;
    }
    public boolean find(int i, int j, String word, char[][] board, boolean [][] flag,int pos) {
    	if(pos == word.length()) {
    		r = true;
    		return true;
    	}
    
    	boolean [][] newflag = new boolean[board.length][board[0].length];
    	int newpos = pos+1;
    	if(flag != null) {
    		if(flag[i][j] == true)
        		return false;
    	for(int m = 0; m < flag.length; i++)
    		for(int n = 0; n <flag[0].length; j++) {
    			newflag[m][n] = flag[m][n];
    		}
    	}
    	newflag[i][j] = true;
    	if(board[i][j] != word.charAt(pos))
    		return false;
    	if(i-1>0){
    		//up
    			if(find(i-1, j, word, board, newflag, newpos))
    				return true;
    	}
    	if(i+1 < board.length) {
    		//down
    			if(find(i+1, j, word, board, newflag, newpos))
    				return true;
    	}
    	if(j-1 > 0) {
    		//left
    			if(find(i, j-1, word, board, newflag, newpos))
    				return true;
    	}
    	if(j+1 < board[0].length) {
    		//right
    			if(find(i, j+1, word, board, newflag, newpos))
    				return true;
    	}
    	return false;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.