描述
典型的九宮格命題: 1 到 9 , 一共10個數, 放在一個 3x3 的表格中,要求表格中的: 同行, 同列 並且 對角線 的所有數字相加 等於 15.
問題分析
這個是一個典型的題目,因爲數據量比較少,所以完全可以用窮舉法實現。
代碼
def solution()
used = []
items = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
numbers = (1..9).to_a
current_num = 1
help(items, current_num, used, numbers)
return items
end
def relation(num, flag = 'x')
x_y = {
1 => [0, 0],
2 => [0, 1],
3 => [0, 2],
4 => [1, 0],
5 => [1, 1],
6 => [1, 2],
7 => [2, 0],
8 => [2, 1],
9 => [2, 2]
}[num]
flag == 'x' ? x_y.first : x_y.last
end
def help(a, current_num, used, numbers)
if current_num == 10
if validate(a)
p a
end
return
end
numbers.each do |num|
next if used[num]
x = relation(current_num, 'x')
y = relation(current_num, 'y')
a[x][y] = num
used[num] = true
help(a, current_num + 1, used, numbers)
a[x][y] = 0
used[num] = false
end
end
def validate(a)
a[0][0] + a[0][1] + a[0][2] == 15 &&
a[0][0] + a[1][0] + a[2][0] == 15 &&
a[0][0] + a[1][1] + a[2][2] == 15 &&
a[1][0] + a[1][1] + a[1][2] == 15 &&
a[2][0] + a[2][1] + a[2][2] == 15 &&
a[0][1] + a[1][1] + a[2][1] == 15 &&
a[0][2] + a[1][1] + a[2][0] == 15 &&
a[1][1] == 5
end
solution
基本思路:
1. 窮舉所有的可能情況
- 使用 遞歸 方法,窮舉所有的可能值
- 用一個數組 used 來記錄哪些值已經被使用了,因爲在同一個二維數組中,不能出現重複的數
- 每次迭代結束後,需要重置數組的值
2. 判斷是否滿足“同行,同列,對角線”的數之和爲15
運行結果
[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
[[2, 9, 4], [7, 5, 3], [6, 1, 8]]
[[4, 3, 8], [9, 5, 1], [2, 7, 6]]
[[4, 9, 2], [3, 5, 7], [8, 1, 6]]
[[6, 1, 8], [7, 5, 3], [2, 9, 4]]
[[6, 7, 2], [1, 5, 9], [8, 3, 4]]
[[8, 1, 6], [3, 5, 7], [4, 9, 2]]
[[8, 3, 4], [1, 5, 9], [6, 7, 2]]