Given an N-by-N grid with each cell either occupied by an 'X', an 'O', or empty, write a program to find the longest sequence of consecutive 'X's either horizontal, vertically, or diagonally. To test your program, you can create a random grid where each cell contains an 'X' or 'O' with probability 1/3.I would like a review of my answer. I'm not sure it's efficient enough, or even efficient at all. I chose to use numbers for now since they easier to work with. I hope it's all clear. class Main {    public static void main(String[] args){        int n = 4;        int[][] grid = new int[n][n];        int max =  Integer.MIN_VALUE;        for(int i = 0; i < n; i++){            for(int j = 0; j < n; j++){                // three nums are produced. there is 1/3 chance for each.                int r = (int)(Math.random()*3);                // both 'X' and 'O' have 1/3 chance to be produced.                 if(r == 1) grid[i][j] = 1;                if(r == 2) grid[i][j] = 2;                System.out.print(grid[i][j]+ );            }            System.out.println();        }        // horizontal, vertical, backward diag, forward diag        int hori  = 0, vert = 0, bdia = 0, fdia = 0;        // assuming 1 represents 'X' and 2 represents 'O'        int num   = (int)(1 + Math.random()*2);        for(int i = 0; i < n; i++){            hori = 0; vert = 0;            // horizontal instances              for(int j = 0; j < n; j++){                if(grid[i][j] != num)                    hori = 0;                else hori ++;                max = hori > max? hori: max;            }            // vertical  instances             for(int j = 0; j < n; j++){                if(grid[j][i] != num)                    vert = 0;                else vert ++;                max = vert > max? vert: max;            }            // forward diag instances (fdia)            for(int j = 0; j < n && i == 0; j++){                if(grid[j][j] != num)                    fdia = 0;                else fdia ++;                max = fdia > max? fdia: max;            }            // backward diag instances (bdia)             for(int j = 0; j < n && i == 0; j++){                if(grid[j][n-1-j] != num)                    bdia = 0;                else bdia ++;                max = bdia > max? bdia: max;            }        }        System.out.println(max : +max);        System.out.println(num : +num);    }}
Longest sequence of same subsequent number in a square matrix
java;performance;beginner