[알고리즘] LeetCode - Word Search
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.
입출력 예시
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;
}
}
Author And Source
이 문제에 관하여([알고리즘] LeetCode - Word Search), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jerry92/알고리즘-LeetCode-Word-Search저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)