79. Word Search (Medium)

https://leetcode.com/problems/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.

Example:

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

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Hints

Solutions

  • Java
class Solution {
    private final int[] R = {0, 0, 1, -1};
    private final int[] C = {1, -1, 0, 0};
    private boolean[][] visited;
    private int length = 0, N, M;

    public boolean exist(char[][] board, String word) {
        N = board.length;
        M = board[0].length;
        if (N * M < word.length()) return false;
        visited = new boolean[N][M];
        length = word.length();
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (board[i][j] == word.charAt(0)) {
                    if (dfs(i, j, board, word, 1)) return true;
                    visited[i][j] = false;
                }
            }
        }
        return false;
    }

    boolean dfs(int r, int c, char[][] board, String word, int pos) {
        if (pos >= length) return true;

        if (pos < length) {
            visited[r][c] = true;
            for (int i = 0; i < 4; i++) {
                int newR = r + R[i];
                int newC = c + C[i];
                if (newR >= 0 && newR < N && newC >= 0 && newC < M) {
                    if (!visited[newR][newC]) {
                        if (board[newR][newC] == word.charAt(pos)) {
                            if (dfs(newR, newC, board, word, pos + 1)) return true;
                            visited[newR][newC] = false;
                        }
                    }
                }
            }
        }

        return false;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-08 13:18:49

results matching ""

    No results matching ""