Title: Word Search Source: leetcode.com
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.
For example,
Given board =
1 2 3 4 5 |
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] |
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
Java solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/* https://leetcode.com/problems/word-search/ */ import java.util.Arrays; class WordSearch { public static void main(String args[]) { char[][] board = { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }; WordSearch ws = new WordSearch(); String word = "SEE"; System.out.println(ws.exist(board, word)); } public boolean exist(char[][] board, String word) { boolean[][] visited = new boolean[board.length][board[0].length]; for(int i=0;i<board.length;i++) Arrays.fill(visited[i], false); for(int i=0;i<board.length;i++) { for(int j=0;j<board[i].length;j++) { //System.out.println("-----------"); if(existHelper(i, j, board, word, 0, visited)) return true; } } return false; } //Backtracking public boolean existHelper(int i, int j, char[][] board, String word, int pos, boolean[][] visited) { if(pos==word.length()) return true; if(isSafe(i, j, board, word, pos, visited)) { //System.out.println("row: "+i+" col: "+j+" pos: "+pos); visited[i][j] = true; if(existHelper(i+1, j, board, word, pos+1, visited)) return true; if(existHelper(i, j+1, board, word, pos+1, visited)) return true; if(existHelper(i-1, j, board, word, pos+1, visited)) return true; if(existHelper(i, j-1, board, word, pos+1, visited)) return true; visited[i][j] = false; } return false; } public boolean isSafe(int row, int col, char[][] board, String word, int pos, boolean [][] visited) { if(row<board.length && row>=0 && col < board[row].length && col >=0 && visited[row][col]!=true && board[row][col]==word.charAt(pos)) return true; return false; } } |