MCPcopy Create free account
hub / github.com/careercup/ctci / hasWon3

Method hasWon3

java/Chapter 17/Question17_2/QuestionB.java:95–153  ·  view source on GitHub ↗
(Piece[][] board)

Source from the content-addressed store, hash-verified

93
94 /* NxN solution */
95 public static Piece hasWon3(Piece[][] board) {
96 int N = board.length;
97 int row = 0;
98 int col = 0;
99
100 // Check rows
101 for (row = 0; row < N; row++) {
102 if (board[row][0] != Piece.Empty) {
103 for (col = 1; col < N; col++) {
104 if (board[row][col] != board[row][col-1]) {
105 break;
106 }
107 }
108 if (col == N) {
109 return board[row][0];
110 }
111 }
112 }
113
114 // Check columns
115 for (col = 0; col < N; col++) {
116 if (board[0][col] != Piece.Empty) {
117 for (row = 1; row < N; row++) {
118 if (board[row][col] != board[row-1][col]) {
119 break;
120 }
121 }
122 if (row == N) {
123 return board[0][col];
124 }
125 }
126 }
127
128 // Check diagonal (top left to bottom right)
129 if (board[0][0] != Piece.Empty) {
130 for (row = 1; row < N; row++) {
131 if (board[row][row] != board[row-1][row-1]) {
132 break;
133 }
134 }
135 if (row == N) {
136 return board[0][0];
137 }
138 }
139
140 // Check diagonal (bottom left to top right)
141 if (board[N-1][0] != Piece.Empty) {
142 for (row = 1; row < N; row++) {
143 if (board[N-row-1][row] != board[N-row][row-1]) {
144 break;
145 }
146 }
147 if (row == N) {
148 return board[N-1][0];
149 }
150 }
151
152 return Piece.Empty;

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected