Attempting the Eight Queens problem in Python (https://open.kattis.com/problems/8queens).
I've written some code which works for all input I've been able to imagine for the last hour - but the program still fails the Kattis test cases.
It's not very efficient, or well structured, but since the problem shouldn't require speed I didn't really care.
What I'm doing is checking every position, if there is a queen there - I check horizontally, vertically, and diagonally. I figured that it's probably the diagonal checking code that's wrong since the other 2 are very straightforward, but I can't figure it out...
Edit: Request to paste code in question, don't see why but sure:
Edit2: Edited code by adding counter to make sure there are 8 queens.
Edit3: Fixed last bug, code is now working!
import sys
import math
def horizontal(j, row):
for k in range(8):
if k == j:
continue
if row[k] == '*':
return False
return True
def vertical(rows, row , column):
for i in range(8):
if i == row:
continue
if rows[i][column] == '*':
return False
return True
def diagonal(rows, row, column):
#first diagonal
current_row = row
current_col = column
#go furthest up
while True:
if current_col == 0 or current_row == 0:
break
current_col-=1
current_row-=1
while True:
if current_row == row and current_col == column:
if current_col == 7 or current_row == 7:
break
current_col += 1
current_row += 1
continue
if rows[current_row][current_col] == '*':
return False
if current_col == 7 or current_row == 7:
break
current_col += 1
current_row += 1
#other diagonal
current_row = row
current_col = column
while True:
if current_col == 7 or current_row == 0:
break
current_col+=1
current_row-=1
while True:
if current_row == row and current_col == column:
if current_col == 0 or current_row == 7:
break
current_col -= 1
current_row += 1
continue
if rows[current_row][current_col] == '*':
return False
if current_col == 0 or current_row == 7:
break
current_col -= 1
current_row += 1
return True
rows = []
for i in range(8):
rows.append(sys.stdin.readline().rstrip())
valid = True
counter = 0
#for every row:
for row in range(8):
for column in range(8):
if rows[row][column] == '*':
counter += 1
if not (horizontal(column,rows[row]) and vertical(rows, row, column) and diagonal(rows, row, column)):
valid = False
break
if not valid:
break
if valid and counter == 8:
print("valid")
else:
print("invalid")