Skip to content

Commit 5cf7822

Browse files
authored
Added solution for check if move is legal. (#394)
1 parent 20858f2 commit 5cf7822

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

C++/check-if-move-is-legal.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public:
3+
bool search(vector<vector<char>>& board, int rMove, int cMove, char g_color, int i, int j)
4+
{
5+
rMove += i;
6+
cMove += j;
7+
int turn = 1;
8+
9+
10+
// Loop over the path until either condition is certain
11+
while(rMove < 8 && cMove < 8 && rMove >= 0 && cMove >= 0
12+
&& board[rMove][cMove] != '.')
13+
{
14+
if(turn > 1 && board[rMove][cMove] == g_color) {return true;}
15+
else if(board[rMove][cMove] == g_color) return false;
16+
turn++;
17+
rMove += i;
18+
cMove += j;
19+
}
20+
21+
return false;
22+
}
23+
bool checkMove(vector<vector<char>>& board, int rMove, int cMove, char color) {
24+
// A problem about searching the cells around and checking conditions
25+
// Eight different moving patterns that needs to be checked
26+
// For each pattern we need to ensure that the first next two celles are the
27+
// opposite color. After this, we need to find a same color.
28+
// If no such exist (either boundary conditions or ".") then return false
29+
// OR the results together and return
30+
31+
// Early termination:
32+
if(board[rMove][cMove] != '.')
33+
{
34+
return false;
35+
}
36+
37+
38+
// Loop over all possible combinations of row and column traversal
39+
for(int i = -1; i <= 1; i++)
40+
{
41+
for(int j = -1; j <= 1; j++)
42+
{
43+
if(search(board, rMove, cMove, color, i, j))
44+
{
45+
return true;
46+
}
47+
}
48+
}
49+
return false;
50+
}
51+
};

0 commit comments

Comments
 (0)