|
| 1 | +package ood.design; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class ConnectGame { |
| 6 | + |
| 7 | + private char[][] grid; |
| 8 | + private int row,col; |
| 9 | + private Map<Integer, Set<Character>> currentScore ; |
| 10 | + private Map<Character,Integer> playerScore; |
| 11 | + |
| 12 | + public ConnectGame(int r , int c){ |
| 13 | + grid = new char[r][c]; |
| 14 | + row = r;col = c; |
| 15 | + for(int i = 0; i < r; i++) { |
| 16 | + for(int j = 0; j < c; j++) { |
| 17 | + grid[i][j] = '*'; |
| 18 | + } |
| 19 | + } |
| 20 | + currentScore = new TreeMap<>(Comparator.reverseOrder()); |
| 21 | + playerScore = new HashMap<>(); |
| 22 | + } |
| 23 | + |
| 24 | + public boolean isWinner(int column,int r, char c){ |
| 25 | + return playerScore.get(c) > 2 ; |
| 26 | + } |
| 27 | + |
| 28 | + private int getDFS(int r, int c, char _c, boolean[][] visited){ |
| 29 | + if(r < 0 || c < 0 || r >= row || c >= col || visited[r][c] || grid[r][c] != _c){ |
| 30 | + return 0; |
| 31 | + } |
| 32 | + visited[r][c] = true; |
| 33 | + return 1 + getDFS(r,c+1,_c,visited) + |
| 34 | + getDFS(r,c-1,_c,visited) + |
| 35 | + getDFS(r+1,c,_c,visited) + |
| 36 | + getDFS(r-1,c,_c,visited) ; |
| 37 | + } |
| 38 | + |
| 39 | + public void element(int column , char c){ |
| 40 | + int r = row-1; |
| 41 | + while(r >= 0 && grid[r][column]!='*'){ |
| 42 | + r--; |
| 43 | + } |
| 44 | + grid[r][column] = c; |
| 45 | + addScore(r,column,c); |
| 46 | + if(isWinner(r,column,c)) |
| 47 | + System.out.println("Winner !! "); |
| 48 | + } |
| 49 | + |
| 50 | + private void addScore(int r, int column, char c){ |
| 51 | + int oldScore = playerScore.getOrDefault(c,0); |
| 52 | + int newScore = Math.max(getDFS(r,column,c,new boolean[row][col]) , oldScore); |
| 53 | + |
| 54 | + if(currentScore.containsKey(oldScore)){ |
| 55 | + currentScore.get(oldScore).remove(c); |
| 56 | + if(currentScore.get(oldScore).isEmpty()) |
| 57 | + currentScore.remove(oldScore); |
| 58 | + } |
| 59 | + |
| 60 | + currentScore.putIfAbsent(newScore,new HashSet<>()); |
| 61 | + currentScore.get(newScore).add(c); |
| 62 | + |
| 63 | + playerScore.put(c,newScore); |
| 64 | + } |
| 65 | + |
| 66 | + public void print(){ |
| 67 | + for(int i = 0; i < row; i++) { |
| 68 | + for(int j = 0; j < col ; j++) { |
| 69 | + System.out.print(grid[i][j] + " "); |
| 70 | + } |
| 71 | + System.out.println(); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + public static void main(String[] args){ |
| 76 | + ConnectGame game = new ConnectGame(4,4); |
| 77 | + game.element(0,'R'); |
| 78 | + game.element(1,'B'); |
| 79 | + game.element(1,'B'); |
| 80 | + game.element(1,'B'); |
| 81 | + game.print(); |
| 82 | + System.out.println(game.currentScore); |
| 83 | + } |
| 84 | +} |
0 commit comments