-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathWordsearch.java
More file actions
49 lines (41 loc) · 1.31 KB
/
Wordsearch.java
File metadata and controls
49 lines (41 loc) · 1.31 KB
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
package sheetquestions;
import java.util.Scanner;
public class Wordsearch {
static int c = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char[][] arr = { { 'A', 'B', 'C', 'E' }
, { 'S', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' } };
String word = s.next();
char ch=word.charAt(0);
for(int i=0;i<arr.length;i++) {
for(int j=0;j<arr[0].length;j++) {
if(arr[i][j]==ch) {
boolean[][] visited = new boolean[arr.length][arr[0].length];
wordsearch(arr, "", i, j, word, visited);
}
}
}
if (c == 1)
System.out.println("true");
else
System.out.println("false");
}
public static void wordsearch(char[][] board, String ans, int row, int col, String word, boolean[][] visited) {
if (ans.equals(word)) {
c = 1;
return;
}
if (row == board.length || col == board[0].length || row < 0 || col < 0 || visited[row][col]) {
return;
}
visited[row][col] = true;
char ch = board[row][col];
wordsearch(board, ans + ch, row + 1, col, word, visited);
wordsearch(board, ans + ch, row - 1, col, word, visited);
wordsearch(board, ans + ch, row, col + 1, word, visited);
wordsearch(board, ans + ch, row, col - 1, word, visited);
visited[row][col] = false;
}
}