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.

Solutions

class Solution {
    private final int[] R = new int[]{0, 0, 1, -1};
    private final int[] C = new int[]{1, -1, 0, 0};

    private int row;
    private int col;

    private boolean[][] visited;

    public boolean exist(char[][] board, String word) {
        if (word == null || word.equals("")) {
            return true;
        }

        if (board == null) {
            return false;
        }

        row = board.length;
        col = board[0].length;

        if (row * col < word.length()) {
            return false;
        }

        visited = new boolean[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] != word.charAt(0)) {
                    continue;
                }

                if (dfs(i, j, board, word, 1)) {
                    return true;
                }
            }
        }

        return false;
    }

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

        // set visited since same cell can not be used twice
        visited[r][c] = true;
        for (int i = 0; i < 4; i++) {
            int newR = r + R[i];
            int newC = c + C[i];

            // overstep the boundary
            if (newR < 0 || newR >= row || newC < 0 || newC >= col) {
                continue;
            }

            if (visited[newR][newC]) {
                continue;
            }

            if (board[newR][newC] != word.charAt(pos)) {
                continue;
            }

            if (dfs(newR, newC, board, word, pos + 1)) {
                return true;
            }
        }

        // reset for next round of searching
        visited[r][c] = false;

        return false;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""