-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqueens-that-can-attack-the-king.rs
97 lines (83 loc) · 2.47 KB
/
queens-that-can-attack-the-king.rs
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
#![allow(dead_code, unused, unused_variables, non_snake_case)]
use std::collections::HashSet;
use serde::de::Unexpected::Option;
use tera::Filter;
fn main() {}
struct Solution;
impl Solution {
pub fn queens_attackthe_king(queens: Vec<Vec<i32>>, king: Vec<i32>) -> Vec<Vec<i32>> {
use std::collections::HashSet;
let hash: HashSet<_> = queens.into_iter().collect();
// 枚举8个方向,遇到的第一个就行
let mut result = vec![];
let mut s = king[0];
while s >= 1 {
if hash.contains(&vec![s - 1, king[1]]) {
result.push(vec![s - 1, king[1]]);
break;
}
s -= 1;
}
let mut s = king[0];
while s <= 6 {
if hash.contains(&vec![s + 1, king[1]]) {
result.push(vec![s + 1, king[1]]);
break;
}
s += 1;
}
let mut s = king[1];
while s >= 1 {
if hash.contains(&vec![king[0], s - 1]) {
result.push(vec![king[0], s - 1]);
break;
}
s -= 1;
}
let mut s = king[1];
while s <= 6 {
if hash.contains(&vec![king[0], s + 1]) {
result.push(vec![king[0], s + 1]);
break;
}
s += 1;
}
let (mut s1, mut s2) = (king[0], king[1]);
while s1 >= 1 && s2 >= 1 {
if hash.contains(&vec![s1 - 1, s2 - 1]) {
result.push(vec![s1 - 1, s2 - 1]);
break;
}
s1 -= 1;
s2 -= 1;
}
let (mut s1, mut s2) = (king[0], king[1]);
while s1 <= 6 && s2 <= 6 {
if hash.contains(&vec![s1 + 1, s2 + 1]) {
result.push(vec![s1 + 1, s2 + 1]);
break;
}
s1 += 1;
s2 += 1;
}
let (mut s1, mut s2) = (king[0], king[1]);
while s1 >= 0 && s2 <= 6 {
if hash.contains(&vec![s1 - 1, s2 + 1]) {
result.push(vec![s1 - 1, s2 + 1]);
break;
}
s1 -= 1;
s2 += 1;
}
let (mut s1, mut s2) = (king[0], king[1]);
while s1 <= 6 && s2 >= 0 {
if hash.contains(&vec![s1 + 1, s2 - 1]) {
result.push(vec![s1 + 1, s2 - 1]);
break;
}
s1 += 1;
s2 -= 1;
}
result
}
}