Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit04a0f72

Browse files
authored
added solution and test case for 79 (#150)
1 parent58bdfd2 commit04a0f72

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
returnfalse;
4141
}
4242
}
43+
44+
// O(1) space solution
45+
publicstaticclassSolution2 {
46+
publicbooleanexist(char[][]board,Stringword) {
47+
48+
// do DFS traversal
49+
introw =board.length;
50+
intcol =board[0].length;
51+
52+
for (inti =0;i <row;i++) {
53+
for (intj =0;j <col;j++) {
54+
if (board[i][j] ==word.charAt(0) &&search(board,i,j,word,0) ==true)
55+
returntrue;
56+
}
57+
}
58+
returnfalse;
59+
}
60+
61+
privatebooleansearch(char[][]board,inti,intj,Stringword,intindex) {
62+
if (index ==word.length() -1)
63+
returntrue;
64+
65+
// store the visited char in temp variable
66+
chartemp =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+
returntrue;
70+
if (i <board.length -1 &&board[i +1][j] ==word.charAt(index +1) &&search(board,i +1,j,word,index +1) ==true)
71+
returntrue;
72+
73+
if (j >0 &&board[i][j -1] ==word.charAt(index +1) &&search(board,i,j -1,word,index +1) ==true)
74+
returntrue;
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+
returntrue;
79+
80+
board[i][j] =temp;
81+
returnfalse;
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
publicclass_79Test {
1010
privatestatic_79.Solution1solution1;
11+
privatestatic_79.Solution2solution2;
1112
privatestaticchar[][]board;
1213

1314
@BeforeClass
1415
publicstaticvoidsetup() {
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+
publicvoidtest4() {
56+
board =newchar[][]{
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)

[8]ページ先頭

©2009-2025 Movatter.jp