主要是为了练习Python。
面向过程式:
def can_put(x , y , row_col , grib , flags): if grib[x][y] == 'X': return False j = y - 1 while j >= 0: if flags[x][j] == 1: return False elif grib[x][j] == 'X': break j -= 1 i = x - 1 while i >= 0: if flags[i][y] == 1: return False elif grib[i][y] == 'X': return True i -= 1 return True def dfs(step , cnt , row_col , grib , flags): global ans if step == row_col ** 2 : if cnt > ans: ans = cnt return x = step / row_col y = step % row_col if can_put(x , y , row_col , grib , flags): flags[x][y] = 1 dfs(step + 1 , cnt + 1 , row_col , grib , flags) flags[x][y] = 0 dfs(step + 1 , cnt , row_col , grib , flags) ans = 0 def main(): while True: row_col = int(raw_input()) if row_col == 0: break else: grib = [ raw_input() for row in range(row_col) ] flags = [ [0 for i in range(row_col)] for j in range(row_col)] global ans ans = 0 dfs(0 , 0 , row_col , grib , flags) print ans main()
面向对象式:
class FireNet(object): def __init__(self , row_col , grib , flags): self.ans = 0 self.row_col = row_col self.grib = grib self.flags = flags def can_put(self , x , y): if self.grib[x][y] == 'X': return False j = y - 1 while j >= 0: if self.flags[x][j] == 1: return False elif self.grib[x][j] == 'X': break j -= 1 i = x - 1 while i >= 0: if self.flags[i][y] == 1: return False elif self.grib[i][y] == 'X': return True i -= 1 return True def dfs(self , step , cnt): if step == self.row_col ** 2 : if cnt > self.ans: self.ans = cnt return x = step / self.row_col y = step % self.row_col if self.can_put(x , y): self.flags[x][y] = 1 self.dfs(step + 1 , cnt + 1) self.flags[x][y] = 0 self.dfs(step + 1 , cnt) def main(): while True: row_col = int(raw_input()) if row_col == 0: break else: grib = [ raw_input() for row in xrange(row_col) ] flags = [ [0 for i in xrange(row_col)] for j in xrange(row_col)] aFireNet = FireNet(row_col , grib , flags) aFireNet.dfs(0, 0) print aFireNet.ans main()