# 第四十四周ARTS总结
# Algorithm
6ms | 37.28% Run time
41MB | 5.41% Memory
public List<List<String>> solveNQueens(int n) {
List<String> puzzle = new ArrayList<>();
char[] chs = new char[n];
Arrays.fill(chs, '.');
for (int i = 0; i < n; i++) {
puzzle.add(new String(chs));
}
return fillRest(puzzle, 0);
}
/**
* 根据已填的来继续填写剩下的部分
*
* @param puzzle 已填写部分
* @param index 已填写完成的行数
* @return
*/
private List<List<String>> fillRest(List<String> puzzle, int index) {
List<List<String>> ans = new ArrayList<>();
// 填写第index行
for (int i = 0; i < puzzle.size(); i++) {
if (canFill(puzzle, index, i)) {
List<String> newPuzzle = new ArrayList<>(puzzle);
char[] chs = new char[puzzle.size()];
Arrays.fill(chs, '.');
chs[i] = 'Q';
newPuzzle.set(index, new String(chs));
if (index < puzzle.size() - 1) {
List<List<String>> part = fillRest(newPuzzle, index + 1);
ans.addAll(part);
} else {
ans.add(newPuzzle);
}
}
}
return ans;
}
/**
* 判断索引(x, y)是否可放置皇后
*
* @param puzzle
* @param x
* @param y
* @return
*/
private boolean canFill(List<String> puzzle, int x, int y) {
// 先比较纵向
for (int i = 0; i < x; i++) {
if ('Q' == puzzle.get(i).charAt(y)) {
return false;
}
}
// 再比较斜向
int k = 1;
while ((x - k >= 0 && y - k >= 0) || (x - k >= 0 && y + k <= puzzle.size() - 1)) {
// 当左上角坐标存在
if (x - k >= 0 && y - k >= 0 && 'Q' == puzzle.get(x - k).charAt(y - k)) {
return false;
}
// 当右上角坐标存在
if (x - k >= 0 && y + k <= puzzle.size() - 1 && 'Q' == puzzle.get(x - k).charAt(y + k)) {
return false;
}
++k;
}
return true;
}
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
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
# Review
# Tip
getRawX()
可以获取到View的绝对坐标 [1] (opens new window)translationX
和translationY
是View左上角相对父容器左上角的偏移量,它们默认值是0 [2] (opens new window)TouchSlop
:可通过ViewConfiguration.get(getContext()).getScaledTouchSlop()
获取,指系统所能识别的滑动最小距离 [3] (opens new window)VelocityTracker
:速度追踪,用于追踪手指在滑动过程中的速度,包括水平和竖直方向的速度 [4] (opens new window)GestureDetector
:手势检测,用于辅助检测用户的单击、滑动、长按、双击等行为 [5] (opens new window)- View滑动的几种方式 [6] (opens new window):
scrollTo
/scollBy
LayoutParams
- 动画
layout()
offsetLeftAndRight()
与offsetTopAndBottom()
Scroller
- 延时策略
# Share
暂无内容