解题思路:
1. 分情况讨论即可
1.1 找到对应j的位置
1.2 j上下左右是否有B或J
2.3 j上下左右四个方向是否有C,且无遮挡物
3.4 j上下左右四个方向是否有P,且有一个遮挡物
class Solution: def playchess(self , chessboard ): # write code here row, col = len(chessboard), len(chessboard[0]) # 1. 定位小j location_j = (0, 0) for i in range(row): for j in range(col): if chessboard[i][j] == 'j': location_j = (i, j) break # 2. j上下左右是否有B或J up_location = (location_j[0]-1, location_j[1]) down_location = (location_j[0]+1, location_j[1]) left_location = (location_j[0], location_j[1]-1) right_location = (location_j[0], location_j[1]+1) if up_location[0] >= 0 and chessboard[up_location[0]][up_location[1]] in list("BJ"): return "Happy" if down_location[0] < row and chessboard[down_location[0]][down_location[1]] in list("BJ"): return "Happy" if left_location[1] >= 0 and chessboard[left_location[0]][left_location[1]] in list("BJ"): return "Happy" if right_location[1] < col and chessboard[right_location[0]][right_location[1]] in list("BJ"): return "Happy" # 3. j上下左右四个方向是否有C,且无遮挡物 for up in range(location_j[0]-1, -1, -1): if chessboard[up][location_j[1]] == ".": continue elif chessboard[up][location_j[1]] == "C": return "Happy" else: break for left in range(location_j[1]-1, -1, -1): if chessboard[location_j[0]][left] == ".": continue elif chessboard[location_j[0]][left] == "C": return "Happy" else: break for down in range(location_j[0]+1, row): if chessboard[down][location_j[1]] == ".": continue elif chessboard[down][location_j[1]] == "C": return "Happy" else: break for right in range(location_j[1]+1, col): if chessboard[location_j[0]][right] == ".": continue elif chessboard[location_j[0]][right] == "C": return "Happy" else: break # 4. j上下左右四个方向是否有P,且有一个遮挡物 block = 0 for up in range(location_j[0]-1, -1, -1): if chessboard[up][location_j[1]] == ".": continue elif chessboard[up][location_j[1]] == "P" and block == 1: return "Happy" else: block += 1 if block >= 2: break block = 0 for left in range(location_j[1]-1, -1, -1): if chessboard[location_j[0]][left] == ".": continue elif chessboard[location_j[0]][left] == "P" and block == 1: return "Happy" else: block += 1 if block >= 2: break block = 0 for down in range(location_j[0]+1, row): if chessboard[down][location_j[1]] == ".": continue elif chessboard[down][location_j[1]] == "P" and block == 1: return "Happy" else: block += 1 if block >= 2: break block = 0 for right in range(location_j[1]+1, col): if chessboard[location_j[0]][right] == ".": continue elif chessboard[location_j[0]][right] == "P" and block == 1: return "Happy" else: block += 1 if block >= 2: break return "Sad"