79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

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

For example,
Givenboard=


[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

tag: backtracking

class Solution {
    public boolean exist(char[][] board, String word) {
        int n = board.length, m = board[0].length;
        boolean[][] visited = new boolean[n][m];

        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (board[i][j] == word.charAt(0) && !visited[i][j]){
                    if (dfs(board, i, j, 0, new StringBuilder(), word, visited)) return true;
                }
            }
        }

        return false;
    }

    int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    private boolean dfs(char[][] board, int x, int y, int index, StringBuilder sb, String word, boolean[][] visited){

        if (index == word.length()) return true;
        //System.out.println("x: " + x + " y: " + y + " sb: " + sb);
        if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y] || board[x][y] != word.charAt(index)) return false;



        for (int i = 0; i < 4; i++){
            visited[x][y] = true;
            sb.append(board[x][y]);
            if (dfs(board, x + dirs[i][0], y + dirs[i][1], index + 1, sb, word, visited)) return true;
            visited[x][y] = false;
            sb.setLength(sb.length() - 1);
        }

        return false;
    }
}

results for ""

    No results matching ""