Skip to content

Latest commit

 

History

History
120 lines (88 loc) · 2.97 KB

20210915.md

File metadata and controls

120 lines (88 loc) · 2.97 KB

Algorithm

79. Word Search

Description

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

Solution

class Solution {
    /**
	   ALGORITHM
	   STEP 1: loop over all the cells in the board
	   STEP 2: if the cells character is equal to the first letter in word and dfs call is true
				-> return true
	   STEP 3: the word was never found return false
    */
    public boolean exist(char[][] board, String word) {
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(board[i][j] == word.charAt(0) && dfs(board, i, j, word, 0)){
                    return true;
                }
            }
        }
        return true;
    }

    /*
    Input: char[][] board, int row, int col, String word, int index

    ALGORITHM
        BASE CASE: if index equals the words length
                   -> return true
        BASE CASE: if the row is out of the grid, the col is out of the grid,
				   or the character at row,col does not equal the character in word at index
                    -> return false

        STEP 1: store the current char
        STEP 2: set the current char to ""
        STEP 3: call function in all four valid directions
        STEP 4: set the current char back
        STEP 5: return OR of all four calls
    */
    public boolean dfs(char[][] grid, int row, int col, String word, int index){
        if(index == word.length()){
            return true;
        }

        if(row < 0 || row >= grid.length || col < 0 || col >= grid[row].length
        || grid[row][col] != word.charAt(index)){
            return false;
        }

        char current = word.charAt(index);
        grid[row][col] = ' ';

        boolean result =
                    dfs(grid,row+1,col,word,index+1)
					|| dfs(grid,row,col+1,word,index+1)
					||  dfs(grid,row-1,col,word,index+1)
					|| dfs(grid,row,col-1,word,index+1);

        grid[row][col] = current;
        return result;
    }
}

Discuss

Review

Tip

Share