From 7aaed189938d483dd2407aaf2b41fe621e0021ab Mon Sep 17 00:00:00 2001 From: seungyeonchoi Date: Sat, 5 Dec 2026 02:22:51 -0500 Subject: [PATCH] word search solution Co-Authored-By: Claude Opus 5.5 --- word-search/seungyeonchoi.java | 86 ++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 word-search/seungyeonchoi.java diff --git a/word-search/seungyeonchoi.java b/word-search/seungyeonchoi.java new file mode 100644 index 0000000000..4d62303c6e --- /dev/null +++ b/word-search/seungyeonchoi.java @@ -0,0 +1,86 @@ +class Solution { + /** + For each cell in board, start with i = 0: + At cell (r, c), looking for word[i]: + 1. out of the board? -> return false + 2. already visited? -> return false + 3. not equal to word[i]? -> return false + 4. word[i] is the last letter -> return true + 5. mark visited + 6. explore the 4 adjacent cells for word[i+1] + -> if any of them succeeds, return true + 7. unmark visited, so other paths can use this cell + 8. return false + If any start cell succeeds -> true + If every start cell fails -> false + 한 칸 (r, c)에 들어왔다. 지금 word[i]를 찾는 중이다. + 1. 격자 밖인지 체크 → 밖이면 실패 + 2. 이미 방문한 곳인지 체크 → 방문했으면 실패 + 3. 타겟 글자와 동일한지 체크 → 다르면 실패 + 4. 마지막 글자였다면 → 성공 + 5. 방문 표시 + 6. 상하좌우로 word[i+1]을 찾으러 탐색 → 하나라도 성공하면 성공 + 7. 방문 표시 해제하고 실패 반환 + + 격자의 모든 칸 (r, c)에서: + 위 과정을 i = 0으로 시작 → 성공하면 true + 전부 실패하면 false + */ + /** + Complexity + - time: O(m*n*3^L), m x n is the board size, L is the word length + - try every cell as a start (m*n) + - each step has at most 3 directions, since the previous cell is already visited + - the path is at most L long, so 3^L paths per start + - space: O(m*n + L), visited array + recursion stack + */ + public boolean exist(char[][] board, String word) { + boolean [][] visited = new boolean [board.length][board[0].length]; + int index = 0; + for (int i=0; i= visited.length) { + return false; + } + if(col<0 || col >= visited[0].length) { + return false; + } + + if (visited[row][col]) { + return false; + } + + if (board[row][col] != word.charAt(index)) { + return false; + } + + if (index == word.length()-1) { + return true; + } + + visited[row][col] = true; + if (backTracking(board, word, row-1, col, visited, index+1)) { + return true; + } + if (backTracking(board, word, row+1, col, visited, index+1)) { + return true; + } + if (backTracking(board, word, row, col-1, visited, index+1)) { + return true; + } + if (backTracking(board, word, row, col+1, visited, index+1)) { + return true; + } + visited[row][col] = false; + return false; + } +}