forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2018.java
85 lines (80 loc) · 3.28 KB
/
_2018.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.fishercoder.solutions;
public class _2018 {
public static class Solution1 {
public boolean placeWordInCrossword(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == ' ' || board[i][j] == word.charAt(0)) {
if (canPlaceTopDown(word, board, i, j) || canPlaceLeftRight(word, board, i, j)
|| canPlaceBottomUp(word, board, i, j) || canPlaceRightLeft(word, board, i, j)) {
return true;
}
}
}
}
return false;
}
private boolean canPlaceRightLeft(String word, char[][] board, int row, int col) {
if (col + 1 < board[0].length && (Character.isLowerCase(board[row][col + 1]) || board[row][col + 1] == ' ')) {
return false;
}
int k = 0;
int j = col;
for (; j >= 0 && k < word.length(); j--) {
if (board[row][j] != word.charAt(k) && board[row][j] != ' ') {
return false;
} else {
k++;
}
}
return k == word.length() && (j < 0 || board[row][j] == '#');
}
private boolean canPlaceBottomUp(String word, char[][] board, int row, int col) {
if (row + 1 < board.length && (Character.isLowerCase(board[row + 1][col]) || board[row + 1][col] == ' ')) {
return false;
}
int k = 0;
int i = row;
for (; i >= 0 && k < word.length(); i--) {
if (board[i][col] != word.charAt(k) && board[i][col] != ' ') {
return false;
} else {
k++;
}
}
return k == word.length() && (i < 0 || board[i][col] == '#');
}
private boolean canPlaceLeftRight(String word, char[][] board, int row, int col) {
if (col > 0 && (Character.isLowerCase(board[row][col - 1]) || board[row][col - 1] == ' ')) {
return false;
}
int k = 0;
int j = col;
for (; j < board[0].length && k < word.length(); j++) {
if (board[row][j] != word.charAt(k) && board[row][j] != ' ') {
return false;
} else {
k++;
}
}
return k == word.length() && (j == board[0].length || board[row][j] == '#');
}
private boolean canPlaceTopDown(String word, char[][] board, int row, int col) {
if (row > 0 && (Character.isLowerCase(board[row - 1][col]) || board[row - 1][col] == ' ')) {
return false;
}
int k = 0;
int i = row;
for (; i < board.length && k < word.length(); i++) {
if (board[i][col] != word.charAt(k) && board[i][col] != ' ') {
return false;
} else {
k++;
}
}
return k == word.length() && (i == board.length || board[i][col] == '#');
}
}
}