1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| using System; using System.Collections.Generic; using System.Text;
namespace ChessCover { class ChessCover { private int cols; private int rows; private Status[,] board;
public int getSafe(string[] boardLayout) { rows = boardLayout.Length; cols = boardLayout[0].Length;
board = new Status[rows, cols]; for (int row = 0; row < rows; ++row) for (int col = 0; col < cols; ++col) if (boardLayout[row][col] != 'U') board[row, col] = Status.Piece;
for (int row = 0; row < rows; ++row) for (int col = 0; col < cols; ++col) switch (boardLayout[row][col]) { case 'Q': SetQueen(row, col); break; case 'R': SetRock(row, col); break; case 'B': SetBishop(row, col); break; case 'K': SetKing(row, col); break; case 'P': SetPawn(row, col); break; }
int count = 0; for (int row = 0; row < rows; ++row) for (int col = 0; col < cols; ++col) if (board[row, col] == Status.Safe) ++count;
return count; }
private void SetQueen(int row, int col) { SetRock(row, col); SetBishop(row, col); }
private void SetRock(int row, int col) { Trace(row, col, 0, 1); Trace(row, col, 1, 0); Trace(row, col, 0, -1); Trace(row, col, -1, 0); }
private void SetBishop(int row, int col) { Trace(row, col, 1, 1); Trace(row, col, -1, -1); Trace(row, col, -1, 1); Trace(row, col, 1, -1); }
private void SetKing(int row, int col) { SetUnsafe(row - 2, col - 1); SetUnsafe(row - 1, col - 2); SetUnsafe(row + 2, col + 1); SetUnsafe(row + 1, col + 2); SetUnsafe(row + 2, col - 1); SetUnsafe(row - 2, col + 1); SetUnsafe(row + 1, col - 2); SetUnsafe(row - 1, col + 2); }
private void SetPawn(int row, int col) { SetUnsafe(row - 1, col - 1); SetUnsafe(row + 1, col - 1); SetUnsafe(row - 1, col + 1); SetUnsafe(row + 1, col + 1); }
private void Trace(int row, int col, int offsetRow, int offsetCol) { for (int c = col + offsetCol, r = row + offsetRow; r < rows && c < cols && r >= 0 && c >= 0; r += offsetRow, c += offsetCol) { if (board[r, c] == Status.Piece) break; board[r, c] = Status.Unsafe; } }
private void SetUnsafe(int row, int col) { if (row < rows && col < cols && row >= 0 && col >= 0) if (board[row, col] == Status.Safe) board[row, col] = Status.Unsafe; }
enum Status { Safe, Unsafe, Piece } } }
|