我正在处理SPOJ问题Minimum Knight Moves。现在,当我检查每个单元格的可能移动以确保骑士不会离开国际象棋棋盘时,我有一系列条件语句。
// test initialization of one cell (a1)
int i = 1; //row: a
int j = 1; //col: 1
if (j-2 >= MIN_COL) { // left moves
if (i+1 <= MAX_ROW) {
neighbors.push_back(board[i+1][j-2]);
}
if (i-1 >= MIN_ROW) {
neighbors.push_back(board[i-1][j-2]);
}
}
if (j+2 <= MAX_COL) { // right moves
if (i+1 <= MAX_ROW) {
neighbors.push_back(board[i+1][j+2]);
}
if (i-1 >= MIN_ROW) {
neighbors.push_back(board[i-1][j+2]);
}
}
if (i+2 <= MAX_ROW) { // up moves
if (j+1 <= MAX_COL) {
neighbors.push_back(board[i+2][j+1]);
}
if (j-1 >= MIN_COL) {
neighbors.push_back(board[i+2][j-1]);
}
}
if (i-2 >= MIN_ROW) { // down moves
if (j+1 <= MAX_COL) {
neighbors.push_back(board[i-2][j+1]);
}
if (j-1 <= MIN_COL) {
neighbors.push_back(board[i-2][j-1]);
}
}
&#13;
是否有更简单的方法来实现这一点而无需对所有八种可能的移动进行硬编码?我刚刚学习了位板,并将其视为潜在的解决方案,但是现在我更感兴趣的是学习是否有更好的方法来编写C ++中的上述条件语句块。
答案 0 :(得分:2)
你基本上有8段代码可以检查位置是否在范围内,而push_back则是如此。我首先将其作为一个函数编写,然后调用它八次。 可能涉及更多比较,但我希望优化器会删除大部分比较。
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
# Creating the data
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
xGrid, yGrid = np.meshgrid(y, x)
R = np.sqrt(xGrid ** 2 + yGrid ** 2)
z = np.sin(R)
# Creating the plot
lines = []
line_marker = dict(color='#0066FF', width=2)
for i, j, k in zip(xGrid, yGrid, z):
lines.append(go.Scatter3d(x=i, y=j, z=k, mode='lines', line=line_marker))
layout = go.Layout(
title='Wireframe Plot',
scene=dict(
xaxis=dict(
gridcolor='rgb(255, 255, 255)',
zerolinecolor='rgb(255, 255, 255)',
showbackground=True,
backgroundcolor='rgb(230, 230,230)'
),
yaxis=dict(
gridcolor='rgb(255, 255, 255)',
zerolinecolor='rgb(255, 255, 255)',
showbackground=True,
backgroundcolor='rgb(230, 230,230)'
),
zaxis=dict(
gridcolor='rgb(255, 255, 255)',
zerolinecolor='rgb(255, 255, 255)',
showbackground=True,
backgroundcolor='rgb(230, 230,230)'
)
),
showlegend=False,
)
fig = go.Figure(data=lines, layout=layout)
plot_url = py.plot(fig, filename='wireframe_plot')
&#13;