JAVA---------Very Easy Version to understand!!!!!!!!!!!!!


  • -1
    H
    	public static int DFS(char[][] board, String word, int i, int j, int[][] visited) {
    	int[][] direction = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } };
    	for (int k = 0; k < direction.length; k++) {
    		int New_i = i + direction[k][0];
    		int New_j = j + direction[k][1];
    		if (New_i >= 0 && New_i < board.length && New_j >= 0 && New_j < board[0].length
    				&& board[New_i][New_j] == word.charAt(0) && visited[New_i][New_j] == 0) {
    			visited[New_i][New_j] = 1;
    			if (word.length() == 1 || DFS(board, word.substring(1), New_i, New_j, visited) == 1)
    				return 1;
    			visited[New_i][New_j] = 0;
    		}
    	}
    	return 0;
    }
    
    public boolean exist(char[][] board, String word) {
    	if (board == null || board.length == 0 || word == null || word.length() == 0)
    		return false;
    	int rows = board.length, columns = board[0].length;
    	int[][] visited = new int[rows][columns];
    	for (int i = 0; i < rows; i++)
    		for (int j = 0; j < columns; j++)
    			visited[i][j] = 0;
    
    	for (int i = 0; i < rows; i++)
    		for (int j = 0; j < columns; j++) {
    			if (board[i][j] == word.charAt(0)) {
    				visited[i][j] = 1;
    				if (word.length() == 1 || DFS(board, word.substring(1), i, j, visited) == 1)
    					return true;
    				visited[i][j] = 0;
    			}
    		}
    
    	return false;
    }

  • 1
    S

    you do not have to explicitly put 0 in every entry in visited, by default it is 0, I mean at the time of initialization it is 0.


Log in to reply
 

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