Skip to content

Commit 04a0f72

Browse files
authored
added solution and test case for 79 (fishercoder1534#150)
1 parent 58bdfd2 commit 04a0f72

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/main/java/com/fishercoder/solutions/_79.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,45 @@ boolean search(char[][] board, String word, int i, int j, int pos) {
4040
return false;
4141
}
4242
}
43+
44+
// O(1) space solution
45+
public static class Solution2 {
46+
public boolean exist(char[][] board, String word) {
47+
48+
// do DFS traversal
49+
int row = board.length;
50+
int col = board[0].length;
51+
52+
for (int i = 0; i < row; i++) {
53+
for (int j = 0; j < col; j++) {
54+
if (board[i][j] == word.charAt(0) && search(board, i, j, word, 0) == true)
55+
return true;
56+
}
57+
}
58+
return false;
59+
}
60+
61+
private boolean search(char[][] board, int i, int j, String word, int index) {
62+
if (index == word.length() - 1)
63+
return true;
64+
65+
// store the visited char in temp variable
66+
char temp = board[i][j];
67+
board[i][j] = ' ';
68+
if (i > 0 && board[i - 1][j] == word.charAt(index + 1) && search(board, i - 1, j, word, index + 1) == true)
69+
return true;
70+
if (i < board.length - 1 && board[i + 1][j] == word.charAt(index + 1) && search(board, i + 1, j, word, index + 1) == true)
71+
return true;
72+
73+
if (j > 0 && board[i][j - 1] == word.charAt(index + 1) && search(board, i, j - 1, word, index + 1) == true)
74+
return true;
75+
76+
77+
if (j < board[0].length - 1 && board[i][j + 1] == word.charAt(index + 1) && search(board, i, j + 1, word, index + 1) == true)
78+
return true;
79+
80+
board[i][j] = temp;
81+
return false;
82+
}
83+
}
4384
}

src/test/java/com/fishercoder/_79Test.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,14 @@
88

99
public class _79Test {
1010
private static _79.Solution1 solution1;
11+
private static _79.Solution2 solution2;
1112
private static char[][] board;
1213

1314
@BeforeClass
1415
public static void setup() {
16+
1517
solution1 = new _79.Solution1();
18+
solution2 = new _79.Solution2();
1619
}
1720

1821
@Test
@@ -48,4 +51,14 @@ public void test3() {
4851
assertEquals(false, solution1.exist(board, "aaa"));
4952
}
5053

54+
@Test
55+
public void test4() {
56+
board = new char[][]{
57+
{'A', 'B', 'H', 'I'},
58+
{'K', 'E', 'H', 'S'},
59+
{'A', 'D', 'E', 'E'},
60+
};
61+
assertEquals(true, solution2.exist(board, "ABHISHEK"));
62+
}
63+
5164
}

0 commit comments

Comments
 (0)