-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[算法]棋盘攻击问题 #38
Comments
暴力解第一问:var board = [
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 1]
]
function isAttackedBoard(board) {
const map = {}
const len = board.length
for(let i = 0; i < len; i++) {
let row = board[i]
for(let j = 0; j < row.length; j++) {
const v = row[j]
if(v) {
if(map[`col-${j}`] || map[`row-${i}`]) return true
map[`col-${j}`] = true
map[`row-${i}`] = true
}
}
}
return false
}
console.log(isAttackedBoard(board)) // true |
暴力解第二问在上面的基础上修改 var board = [
[1, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 1]
]
function isAttackedBoard(board) {
const map = {}
const len = board.length
let count = 0
for(let i = 0; i < len; i++) {
let row = board[i]
for(let j = 0; j < row.length; j++) {
const v = row[j]
if(v) {
if(map[`col-${j}`]) count += map[`col-${j}`]
if(map[`row-${i}`]) count += map[`row-${i}`]
map[`col-${j}`] = map[`col-${j}`] ? ++map[`col-${j}`] : 1
map[`row-${i}`] = map[`row-${i}`] ? ++map[`row-${i}`] : 1
}
}
}
return count
}
console.log(isAttackedBoard(board)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
示例:
说明:
第一行第四列,与第四行每四列构成攻击状态,因此该棋盘返回状态为 true,其中第二行 第六列的車没有与任何其他車构成攻击状态
示例:
说明:
第一行第一列,跟第一行第四列和第一行第八列都构成攻击状态,图中出现攻击可能的总次数为 6 次
The text was updated successfully, but these errors were encountered: