-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueensThatCanAttacktheKing.java
144 lines (120 loc) · 3.34 KB
/
QueensThatCanAttacktheKing.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package arrays;
import utils.LeetCode;
import utils.Level;
import java.util.*;
@LeetCode(no = 1222,
title = "Queens That Can Attack the King",
level = Level.MEDIUM,
url = "https://leetcode.com/problems/queens-that-can-attack-the-king/")
public class QueensThatCanAttacktheKing {
public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
List<List<Integer>> attackPos = new ArrayList<>();
int kingX = king[0];
int kingY = king[1];
Set<Pair> qPairs = new HashSet<>();
Set<Pair> result = new HashSet<>();
Pair p = null;
for (int i = 0; i < queens.length; i++) {
qPairs.add(new Pair(queens[i][0], queens[i][1]));
}
for (int i = kingY + 1; i <= 7; i++) {
p = new Pair(kingX, i);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
for (int i = kingY - 1; i >= 0; i--) {
p = new Pair(kingX, i);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
for (int i = kingX - 1; i >= 0; i--) {
p = new Pair(i, kingY);
if (qPairs.contains(p)) {
result.add(p);
break;
}
// vU.add(new Pair(i,kingY));
}
for (int i = kingX + 1; i <= 7; i++) {
p = new Pair(i, kingY);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
int y = kingY;
int x = kingX;
while (y > 0) {
p = new Pair(++x, --y);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
y = kingY;
x = kingX;
while (x > 0) {
p = new Pair(--x, ++y);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
y = kingY;
x = kingX;
while (y > 0 && x > 0) {
p = new Pair(--x, --y);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
y = kingY;
x = kingX;
while (y <= 7 && x <= 7) {
p = new Pair(++x, ++y);
if (qPairs.contains(p)) {
result.add(p);
break;
}
}
for (Pair pair : result) {
List<Integer> pos = new ArrayList<>();
pos.add(pair.x);
pos.add(pair.y);
attackPos.add(pos);
}
return attackPos;
}
class Pair {
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int x;
public int y;
@Override
public String toString() {
return "Pair{" +
"x=" + x +
", y=" + y +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return x == pair.x &&
y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}