Find if exists diagonally, horizontally or vertically in 2D - values ​​one by one

So, I am doing a board game from 19 to 19. This is basically compound 5, called Gomoku.

I want to make an efficient algorithm to find if there are "n" pieces in a string. Data is stored as a 19x19 2D array. But for the sake of the question, let's say, 6x6.

0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 

These are two examples of "5" from 1 line. How can I check HORIZONTAL, VERTICAL and both DIAGONALS?

Here is my inefficient code:

  private boolean firstDiagonalCheck(int x, int y, int num) { int count = 1; int check = 0; boolean rflag = true; boolean lflag = true; int pos = 1; check = turnHuman + 1; while (rflag) { if (x + pos >= 19 || y + pos >= 19) { rflag = false; break; } if (gb.getBoard()[x + pos][y + pos] == check) { count++; pos++; } else { rflag = false; } } pos = 1; while (lflag) { if (x - pos < 0 || y - pos < 0) { lflag = false; break; } if (gb.getBoard()[x - pos][y - pos] == check) { count++; pos++; } else { lflag = false; } } if (count == num) { return true; } return false; } 

This is only one method for the first diagonal. There are 3 more.

How can I make it more efficient and check all 4 directions?

EDIT ####################

What my code does: - Get the position of the part (x, y) - Check both sides (up and down, if vertically), and count how many are in the row - If the number of matches matches the desired one, ("num"), then return true otherwise return false.

It would be better if I checked the WHOLE board each time to see if there were any pieces in a row?

+5
source share
1 answer

 int count=0; boolean Check(int x,int y) { int p1; int p2; if(elementat[x+1][y+1]==1) {p1=1; p2=1;} else if(elementat[x+1][y]==1) {p1=1; p2=0;} else. if(elementat[x+1][y-1]==1) {p1=1; p2=-1;} else. if(elementat[x][y-1]==1) {p1=0;p2=-1;} else. if(elementat[x-1][y-1]==1) {p1=-1; p2=-1;} else. if(elementat[x-1][y]==1) {p1=-1; p2=0;} else. if(elementat[x-1][y+1]==1) {p1=-1; p2=1;} else. if(elementat[x][y+1]==1) {p1=0; p2=1;} Checknext(x,y); Checknextinv(x,y); If(count==5) // 5 means no. of elements to form line {return true} else {return false;} } Checknext(x,y) //19 represents the 19x19 matrix { if((x+p1)<=19 && (x+p1)>=0 && (y+p2)<=19 && (y+p2)>=0) { if(element[x+p1][y+p2]==1) { count++; checknext[x+p1][y+p2]; } } Checknextinv(x,y) { if( (x+(-1*p1))<=19 && (x+(-1*p1))>=0 && (y+(-1*p2))<=19 && (y+(-1*p2))>=0)) { if(element[x+(-1*p1)][y+(-1*p2)]==1 ) { count++; checknextinv[x+(-1*p1)][y+(-1*p2)]; } } 
0
source

Source: https://habr.com/ru/post/1203001/


All Articles