Skip to content
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

Refactored N-Queens problem #848

Merged
merged 6 commits into from
Mar 15, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Changed default value and add heuristic function
  • Loading branch information
ad71 committed Mar 15, 2018
commit 0160556e2434ff17c10d5e5ebe74ecabfdac42a0
22 changes: 16 additions & 6 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -1120,29 +1120,29 @@ class NQueensProblem(Problem):
"""The problem of placing N queens on an NxN board with none attacking
each other. A state is represented as an N-element array, where
a value of r in the c-th entry means there is a queen at column c,
row r, and a value of None means that the c-th column has not been
row r, and a value of -1 means that the c-th column has not been
filled in yet. We fill in columns left to right.
>>> depth_first_tree_search(NQueensProblem(8))
<Node (7, 3, 0, 2, 5, 1, 6, 4)>
"""

def __init__(self, N):
self.N = N
self.initial = tuple([None] * N)
self.initial = tuple([-1] * N)
Problem.__init__(self, self.initial)

def actions(self, state):
"""In the leftmost empty column, try all non-conflicting rows."""
if state[-1] is not None:
if state[-1] is not -1:
return [] # All columns filled; no successors
else:
col = state.index(None)
col = state.index(-1)
return [row for row in range(self.N)
if not self.conflicted(state, row, col)]

def result(self, state, row):
"""Place the next queen at the given row."""
col = state.index(None)
col = state.index(-1)
new = list(state[:])
new[col] = row
return tuple(new)
Expand All @@ -1161,11 +1161,21 @@ def conflict(self, row1, col1, row2, col2):

def goal_test(self, state):
"""Check if all columns filled, no conflicts."""
if state[-1] is None:
if state[-1] is -1:
return False
return not any(self.conflicted(state, state[col], col)
for col in range(len(state)))

def h(self, node):
"""Return number of conflicting queens for a given node"""
num_conflicts = 0
for (r1, c1) in enumerate(node.state):
for (r2, c2) in enumerate(node.state):
if (r1, c1) != (r2, c2):
num_conflicts += self.conflict(r1, c1, r2, c2)

return num_conflicts

# ______________________________________________________________________________
# Inverse Boggle: Search for a high-scoring Boggle board. A good domain for
# iterative-repair and related search techniques, as suggested by Justin Boyan.
Expand Down