0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

79. Word Search

アプローチ

DFS

class Solution {

    public  boolean[][] isVisited;
    public  int height = 0;
    public  int width = 0;

    public boolean exist(char[][] board, String word) {
        height = board.length;
        width = board[0].length;
        isVisited = new boolean[height][width];

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                isVisited = new boolean[height][width];
                if (board[i][j] == word.charAt(0)) {

                      boolean result = dfs(board, word,  i, j, 0);if (result) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
        public  boolean dfs(char[][] board, String word, int i, int j, int index) {

        if (index == word.length()) {
            return true;
        }
        if (i < 0 || board.length <= i || j < 0 || board[0].length <= j || isVisited[i][j] || word.charAt(index) != board[i][j]) {
            return false;
        }

        isVisited[i][j] = true;
        if (dfs(board, word, i + 1, j, index + 1) ||
                dfs(board, word, i - 1, j, index + 1) ||
                dfs(board, word, i, j + 1, index + 1) ||
                dfs(board, word, i, j - 1, index + 1)) {
            return true;
        }
        isVisited[i][j] = false;
        return false;

    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?