[알고리즘] LeetCode - Word Search

Jerry·2021년 9월 5일
0

LeetCode

목록 보기
70/73
post-thumbnail

LeetCode - Word Search

문제 설명

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

제약사항

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.

Solution

[전략]

  • 각 보드를 시작으로 주어진 문자열이 될수있는 연속점이 있는지 확인
  • 2번 방문하는 것을 방지하지 위해 방문 기록 관리.
import java.util.Arrays;

class Solution {
    public boolean exist(char[][] board, String word) {

        boolean[][] visits = new boolean[board.length][board[0].length];

        for (boolean[] visit : visits) {
            Arrays.fill(visit, false);
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                // System.out.println("i , j :"+ i+ " : "+j);
                if (backtracking(board, visits, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean backtracking(char[][] board, boolean[][] visits, int i, int j, String word, int len) {

        if (board[i][j] == word.charAt(len)) {

            if (word.length() == len + 1) {
                return true;
            }
            visits[i][j] = true;
            boolean up = i <= 0 || visits[i - 1][j] ? false : backtracking(board, visits, i - 1, j, word, len + 1);
            boolean down = i >= board.length - 1 || visits[i + 1][j] ? false
                    : backtracking(board, visits, i + 1, j, word, len + 1);
            boolean left = j <= 0 || visits[i][j - 1] ? false : backtracking(board, visits, i, j - 1, word, len + 1);
            boolean right = j >= board[0].length - 1 || visits[i][j + 1] ? false
                    : backtracking(board, visits, i, j + 1, word, len + 1);

            visits[i][j] = false;
            return up || down || left || right;
        }
        return false;
    }
}
profile
제리하이웨이

0개의 댓글