Develop / Leetcode April 3, 2024

Daily Question – 79. Word Search

Description: https://leetcode.com/problems/word-search/description/?envType=daily-question&envId=2024-04-03

Notes:

BFS and backtracking. Using a boolean 2-D array to reserve the status of the character whether it ha been selected.

Code:

public class Solution {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        boolean[][] check = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == words[0]) {
                    for (int m = 0 ; m < board.length; m++)
                        for (int n=0; n < board[0].length; n++) check[m][n] = false;
                   if (explore(board,check,i,j,word,0)) return true;
                }
            }
        }
        return false;
    }

    public static boolean explore(char[][] board, boolean[][] check ,int i, int j, String word,int n) {
        if (n >= word.length()) return true;
        if (i<0 || j <0 || i >= board.length || j >= board[0].length || check[i][j]) return false;
        if (board[i][j] != word.charAt(n) ) return false;
        check[i][j] = true;
        boolean result = ( explore(board,check,i+1,j,word,n+1) || explore(board,check,i-1,j,word,n+1) || explore(board,check,i,j+1,word,n+1) || explore(board,check,i,j-1,word,n+1) );
        if (!result) {
            check[i][j] = false;
        }
        return result;
    }
}

You may also like...

Mar
07
2024
0

Daily Question – 0876. Middle of the Linked List

Implement a ‘two pointers’ algorithm, where one pointer moves at a fast pace, advancing two steps at a time, and the other moves at a slower pace, advancing one step at a time. When the fast pointer reaches the end, return the position of the slow pointer.

Feb
22
2024
0

Daily Question – 0997. Find the Town Judge

Post Views: 41 Description: https://leetcode.com/problems/find-the-town-judge/ Notes:

Mar
31
2023
0

2023 Puzzles of World Map

Post Views: 159 Fortunately, I was able to work from home for two days this week....

Feb
28
2024
0

0513. Find Bottom Left Tree Value

Post Views: 26 Description: https://leetcode.com/problems/find-bottom-left-tree-value/description Notes: BFS Code: