mjain

Matrix

Jul 16th, 2019
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.77 KB | None | 0 0
  1. package testrun;
  2.  
  3. import java.util.Comparator;
  4. import java.util.PriorityQueue;
  5.  
  6. public class Matrix {
  7.  
  8.     public static void rotateClockWise(int[][] mat) {
  9.         int lastRow = mat.length;
  10.         int lastCol = mat[0].length;
  11.         int startRow = 0;
  12.         int startCol = 0;
  13.         while (startRow < lastRow && startCol < lastCol) {
  14.             if (startRow + 1 == lastRow || startCol + 1 == lastCol) {
  15.                 break;
  16.             }
  17.             int prev = mat[startRow + 1][startCol];
  18.             for (int i = startCol; i < lastCol; i++) {
  19.                 int current = mat[startRow][i];
  20.                 mat[startRow][i] = prev;
  21.                 prev = current;
  22.             }
  23.             startRow++;
  24.             for (int i = startRow; i < lastRow; i++) {
  25.                 int current = mat[i][lastCol - 1];
  26.                 mat[i][lastCol - 1] = prev;
  27.                 prev = current;
  28.             }
  29.             lastCol--;
  30.  
  31.             if (startRow < lastRow) {
  32.                 for (int i = lastCol - 1; i >= startCol; --i) {
  33.                     int current = mat[lastRow - 1][1];
  34.                     mat[lastRow - 1][1] = prev;
  35.                     prev = current;
  36.                 }
  37.             }
  38.             lastRow--;
  39.  
  40.             if (startCol < lastCol) {
  41.                 for (int i = lastRow - 1; i >= startRow; --i) {
  42.                     int current = mat[i][startCol];
  43.                     mat[i][startCol] = prev;
  44.                     prev = current;
  45.                 }
  46.             }
  47.             startCol++;
  48.         }
  49.  
  50.         for (int i = 0; i < mat.length; i++) {
  51.             for (int j = 0; j < mat[0].length; j++)
  52.                 System.out.print(mat[i][j] + " ");
  53.             System.out.print("\n");
  54.         }
  55.     }
  56.  
  57.     public static void printSpiral(int[][] mat) {
  58.         int lastRow = mat.length;
  59.         int lastCol = mat[0].length;
  60.         int startRow = 0;
  61.         int startCol = 0;
  62.         while (startRow < lastRow && startCol < lastCol) {
  63.             for (int i = startCol; i < lastCol; i++) {
  64.                 System.out.print(mat[startRow][i] + " ");
  65.             }
  66.             startRow++;
  67.  
  68.             for (int i = startRow; i < lastRow; i++) {
  69.                 System.out.print(mat[i][lastCol - 1] + " ");
  70.             }
  71.             lastCol--;
  72.  
  73.             if (startRow < lastRow) {
  74.                 for (int i = lastCol - 1; i >= startCol; --i) {
  75.                     System.out.print(mat[lastRow - 1][i] + " ");
  76.                 }
  77.                 lastRow--;
  78.             }
  79.  
  80.             if (startCol < lastCol) {
  81.                 for (int i = lastRow - 1; i >= startRow; --i) {
  82.                     System.out.print(mat[i][startCol] + " ");
  83.                 }
  84.                 startCol++;
  85.             }
  86.         }
  87.     }
  88.  
  89.     // https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/
  90.     public static void rotate90(int mat[][]) {
  91.         int N = mat.length;
  92.         // find transpose of matrix,row->col,col->row
  93.         printMatrix(mat);
  94.         System.out.println();
  95.         transposeMatrix(mat, N);
  96.         System.out.println("After transpose");
  97.         printMatrix(mat);
  98.         System.out.println("");
  99.         reverseEveryColumn(mat);
  100.         System.out.println("After reverse every column");
  101.         printMatrix(mat);
  102.         System.out.println();
  103.     }
  104.  
  105.     public static void rotate180(int mat[][]) {
  106.         int N = mat.length;
  107.         // find transpose of matrix,row->col,col->row
  108.         printMatrix(mat);
  109.         System.out.println();
  110.         transposeMatrix(mat, N);
  111.         reverseEveryColumn(mat);
  112.         transposeMatrix(mat, N);
  113.         reverseEveryColumn(mat);
  114.  
  115.         printMatrix(mat);
  116.         System.out.println();
  117.     }
  118.  
  119.     private static void printMatrix(int[][] mat) {
  120.         for (int i = 0; i < mat.length; i++) {
  121.             for (int j = 0; j < mat[0].length; j++)
  122.                 System.out.print(mat[i][j] + " ");
  123.             System.out.println("");
  124.         }
  125.     }
  126.  
  127.     private static void reverseEveryColumn(int[][] mat) {
  128.         for (int i = 0; i < mat[0].length; i++) {
  129.             for (int j = 0, k = mat[0].length - 1; j < k; j++, k--) {
  130.                 int temp = mat[j][i];
  131.                 mat[j][i] = mat[k][i];
  132.                 mat[k][i] = temp;
  133.             }
  134.         }
  135.     }
  136.  
  137.     private static void transposeMatrix(int[][] mat, int N) {
  138.         for (int i = 0; i < N; i++) {
  139.             for (int j = i; j < N; j++) {
  140.                 int temp = mat[i][j];
  141.                 mat[i][j] = mat[j][i];
  142.                 mat[j][i] = temp;
  143.             }
  144.         }
  145.     }
  146.  
  147.     private static int count;
  148.  
  149.     public static int printMaxSubSquare(int[][] mat) {
  150.         int rows = mat.length;
  151.         int cols = mat[0].length;
  152.         int solution[][] = new int[rows][cols];
  153.         for (int i = 0; i < rows; i++) {
  154.             solution[i][0] = mat[i][0];
  155.         }
  156.         for (int i = 0; i < cols; i++) {
  157.             solution[0][i] = mat[0][i];
  158.         }
  159.  
  160.         for (int i = 1; i < rows; i++) {
  161.             for (int j = 1; j < cols; j++) {
  162.                 if (mat[i][j] == 1) {
  163.                     solution[i][j] = Math.min(solution[i - 1][j], Math.min(solution[i][j - 1], solution[i - 1][j - 1])) + 1;
  164.                 } else {
  165.                     solution[i][j] = 0;
  166.                 }
  167.             }
  168.         }
  169.         int maxSub = solution[0][0];
  170.         int maxX = 0, maxY = 0;
  171.         for (int i = 0; i < rows; i++) {
  172.             for (int j = 0; j < cols; j++) {
  173.                 if (solution[i][j] > maxSub) {
  174.                     maxX = i;
  175.                     maxY = j;
  176.                     maxSub = solution[i][j];
  177.                 }
  178.             }
  179.         }
  180.         System.out.println("maxX:" + maxX);
  181.         System.out.println("maxY:" + maxY);
  182.         System.out.println("maxSub:" + maxSub);
  183.         for (int i = maxX; i > maxX - maxSub; i--) {
  184.             for (int j = maxY; j > maxY - maxSub; j--) {
  185.                 System.out.print(mat[i][j] + " ");
  186.             }
  187.             System.out.println();
  188.         }
  189.  
  190.         return maxSub;
  191.     }
  192.  
  193.     // https://www.geeksforgeeks.org/a-boolean-matrix-question/
  194.  
  195.     public static void markAllOneRowAndColumns(int[][] mat) {
  196.  
  197.         if (mat == null || mat.length == 0) {
  198.             return;
  199.         }
  200.         // print before manipulation
  201.         for (int i = 0; i < mat.length; i++) {
  202.             for (int j = 0; j < mat[0].length; j++) {
  203.                 System.out.print(mat[i][j]);
  204.             }
  205.             System.out.println("");
  206.         }
  207.         int rows = mat.length;
  208.         int cols = mat[0].length;
  209.         boolean isFirstRoeHasOne = false;
  210.         boolean isFirstColumnHasOne = false;
  211.  
  212.         // updating the first row and col if 1
  213.         // is encountered
  214.         for (int i = 0; i < rows; i++) {
  215.             for (int j = 0; j < cols; j++) {
  216.                 if (i == 0 && mat[i][j] == 1)
  217.                     isFirstRoeHasOne = true;
  218.  
  219.                 if (j == 0 && mat[i][j] == 1)
  220.                     isFirstColumnHasOne = true;
  221.  
  222.                 if (mat[i][j] == 1) {
  223.                     mat[0][j] = 1;
  224.                     mat[i][0] = 1;
  225.                 }
  226.             }
  227.         }
  228.         for (int i = 1; i < rows; i++) {
  229.             for (int j = 1; j < cols; j++) {
  230.                 if (mat[0][j] == 1 || mat[i][0] == 1) {
  231.                     mat[i][j] = 1;
  232.                 }
  233.             }
  234.         }
  235.  
  236.         if (isFirstRoeHasOne == true) {
  237.             for (int i = 0; i < cols; i++) {
  238.                 mat[0][i] = 1;
  239.             }
  240.         }
  241.  
  242.         if (isFirstColumnHasOne == true) {
  243.             for (int i = 0; i < rows; i++) {
  244.                 mat[i][0] = 1;
  245.             }
  246.         }
  247.         // print after manipulation
  248.         for (int i = 0; i < mat.length; i++) {
  249.             for (int j = 0; j < mat[0].length; j++) {
  250.                 System.out.print(mat[i][j]);
  251.             }
  252.             System.out.println("");
  253.         }
  254.  
  255.     }
  256.  
  257.     // https://www.geeksforgeeks.org/find-length-largest-region-boolean-matrix/
  258.  
  259.     public static void largestRegion(int[][] mat) {
  260.         if (mat == null || mat.length == 0) {
  261.             return;
  262.         }
  263.         for (int i = 0; i < mat.length; i++) {
  264.             for (int j = 0; j < mat[0].length; j++) {
  265.                 System.out.print(mat[i][j]);
  266.             }
  267.             System.out.println("");
  268.         }
  269.         int rows = mat.length;
  270.         int cols = mat[0].length;
  271.         boolean[][] isVisited = new boolean[rows][cols];
  272.  
  273.         int maxResult = -1;
  274.         for (int i = 0; i < rows; i++) {
  275.             for (int j = 0; j < cols; j++) {
  276.                 if (mat[i][j] == 1 && !isVisited[i][j]) {
  277.                     count = 1;
  278.                     DFS(i, j, mat, isVisited);
  279.                     maxResult = Math.max(maxResult, count);
  280.                 }
  281.             }
  282.         }
  283.         System.out.println("largest region size:" + maxResult);
  284.     }
  285.  
  286.     public static void DFS(int row, int col, int[][] mat, boolean[][] isVisited) {
  287.         int[] neighbourRows = new int[] { -1, -1, 0, 1, 0, 1, -1, 1 };
  288.         int[] neightbourCols = new int[] { -1, 0, -1, 0, 1, 1, 1, -1 };
  289.         int rows = mat.length;
  290.         int cols = mat[0].length;
  291.         isVisited[row][col] = true;
  292.         for (int k = 0; k < 8; k++) {
  293.             if (isSafeToMoveInMatrixDFS(row + neighbourRows[k], rows, col + neightbourCols[k], cols, isVisited, mat)) {
  294.                 count++;
  295.                 DFS(row + neighbourRows[k], row + neighbourRows[k], mat, isVisited);
  296.             }
  297.         }
  298.     }
  299.  
  300.     public static boolean isSafeToMoveInMatrixDFS(int curRow, int maxRow, int curCol, int maxCol,
  301.             boolean[][] isVisited, int[][] mat) {
  302.         return (curRow >= 0 && curRow < maxRow && curCol >= 0 && curCol < maxCol && mat[curRow][curCol] == 1 && !isVisited[curRow][curCol]);
  303.     }
  304.  
  305.     public static void main(String[] args) {
  306.         // int M[][] = { { 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0 }, { 0, 1, 1, 1, 0
  307.         // }, { 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1 },
  308.         // { 0, 0, 0, 0, 0 } };
  309.         // printMaxSubSquare(M);
  310.  
  311.         // int mat[][] = { { 1, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } };
  312.         // markAllOneRowAndColumns(mat);
  313.         // int a[][] = { { 1, 2, 3, 4, 5, 6 }, { 7, 8, 9, 10, 11, 12 }, { 13,
  314.         // 14, 15, 16, 17, 18 } };
  315.         // printSpiral(a);
  316.  
  317.         int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
  318.  
  319.         rotate180(arr);
  320.     }
  321.  
  322.     public static int getpossiblePathInMatFromLeftTopToRightBottom(int[][] mat) {
  323.  
  324.         int m = mat.length;
  325.         int n = mat[0].length;
  326.         for (int i = 0; i < m; i++) {
  327.             if (mat[i][0] == 0) {
  328.                 mat[i][0] = 1;
  329.             }
  330.             break;
  331.         }
  332.         for (int j = 0; j < n; j++) {
  333.             if (mat[0][j] == 0) {
  334.                 mat[0][j] = 1;
  335.             }
  336.             break;
  337.         }
  338.         for (int i = 1; i < m - 1; i++) {
  339.             for (int j = 1; j < n - 1; j++) {
  340.                 if (mat[i][j] == -1) {
  341.                     continue;
  342.                 }
  343.                 if (mat[i - 1][j] > 0) {
  344.                     mat[i][j] += mat[i - 1][j];
  345.                 }
  346.                 if (mat[i][j - 1] > 0) {
  347.                     mat[i][j] += mat[i][j - 1];
  348.                 }
  349.             }
  350.         }
  351.  
  352.         return mat[m - 1][n - 1];
  353.  
  354.     }
  355.  
  356.     public static class Node {
  357.         int x;
  358.         int y;
  359.         int val;
  360.  
  361.         public int getX() {
  362.             return x;
  363.         }
  364.  
  365.         public void setX(int x) {
  366.             this.x = x;
  367.         }
  368.  
  369.         public int getY() {
  370.             return y;
  371.         }
  372.  
  373.         public void setY(int y) {
  374.             this.y = y;
  375.         }
  376.  
  377.         public int getVal() {
  378.             return val;
  379.         }
  380.  
  381.         public void setVal(int val) {
  382.             this.val = val;
  383.         }
  384.  
  385.         public Node(int x, int y, int val) {
  386.             super();
  387.             this.x = x;
  388.             this.y = y;
  389.             this.val = val;
  390.         }
  391.  
  392.     }
  393.  
  394.     public static void KthLargestElem() {
  395.         // matrix is sorted find kth largest,Soltion is klogn
  396.         int mat[][] = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
  397.  
  398.         // create a max heap
  399.         PriorityQueue<Node> minHeap = new PriorityQueue<Node>(new Comparator<Node>() {
  400.             @Override
  401.             public int compare(Node o1, Node o2) {
  402.                 return o2.val - o1.val;
  403.             }
  404.         });
  405.         // take required K
  406.         int k = 7;
  407.         // insert last column in max heap;
  408.         for (int i = 0; i < mat.length; i++) {
  409.             minHeap.offer(new Node(i, mat.length - 1, mat[i][mat.length - 1]));
  410.         }
  411.  
  412.         // replace in max heap from previous column k times
  413.         while (!minHeap.isEmpty()) {
  414.             Node node = minHeap.poll();
  415.             if (k == 1) {
  416.                 // output
  417.                 System.out.print(node.val);
  418.             }
  419.  
  420.             if (node.y - 1 >= 0) {
  421.                 minHeap.offer(new Node(node.x, node.y - 1, mat[node.x][node.y - 1]));
  422.             }
  423.             k--;
  424.         }
  425.  
  426.     }
  427.  
  428.     public static boolean isSafeToMove(int[][] mat, int x, int y) {
  429.         return x >= 0 && x < mat.length && y >= 0 && y < mat[0].length && mat[x][y] > 0;
  430.     }
  431.  
  432.     public static void ratMazeProblem(int[][] mat) {
  433.         int[][] sol = new int[mat.length][mat[0].length];
  434.         if (isPossiblePathForRat(mat, sol, 0, 0)) {
  435.             // print sol
  436.         }
  437.     }
  438.  
  439.     public static boolean isPossiblePathForRat(int[][] mat, int[][] sol, int x, int y) {
  440.         if (x == mat.length - 1 && y == mat[0].length - 1) {
  441.             sol[x][y] = 1;
  442.             return true;
  443.         }
  444.         if (isSafeToMove(mat, x, y)) {
  445.             sol[x][y] = 1;
  446.             if (isPossiblePathForRat(mat, sol, x + 1, y)) {
  447.                 return true;
  448.             }
  449.  
  450.             if (isPossiblePathForRat(mat, sol, x, y + 1)) {
  451.                 return true;
  452.             }
  453.             sol[x][y] = 0;
  454.         }
  455.  
  456.         return false;
  457.     }
  458.  
  459.     public static void searchWord(char[][] matrix, String word, int curIndexAtWord, StringBuilder buf, int curRow,
  460.             int curCol, int prevRow, int prevCol) {
  461.         int rowNum[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
  462.         int colNum[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
  463.         int ROW = matrix.length;
  464.         int COL = matrix[0].length;
  465.         if (curIndexAtWord > word.length()) {
  466.             return;
  467.         }
  468.         if (word.charAt(curIndexAtWord) != matrix[curRow][curCol]) {
  469.             return;
  470.         }
  471.  
  472.         buf.append(word.charAt(curIndexAtWord) + " at (" + curRow + "," + curCol + ")");
  473.         if (curIndexAtWord == word.length() - 1) {
  474.             System.out.println("Path found: " + buf.toString());
  475.             return;
  476.         }
  477.  
  478.         for (int k = 0; k < 8; ++k) {
  479.             if (isvalid(curRow + rowNum[k], curCol + colNum[k], prevRow, prevCol, ROW, COL)) {
  480.                 searchWord(matrix, word, curIndexAtWord + 1, buf, curRow + rowNum[k], curCol + colNum[k], curRow,
  481.                         curCol);
  482.             }
  483.         }
  484.  
  485.     }
  486.  
  487.     static boolean isvalid(int row, int col, int prevRow, int prevCol, int ROW, int COL) {
  488.         return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row == prevRow && col == prevCol);
  489.     }
  490.  
  491.     public static void findoccurenceOFwordInMatrix(char[][] matrix, String word) {
  492.         if (matrix == null || word == null || matrix.length == 0 || word.isEmpty()) {
  493.             return;
  494.         }
  495.         for (int row = 0; row < matrix.length; row++) {
  496.             for (int col = 0; col < matrix[0].length; col++) {
  497.                 StringBuilder buf = new StringBuilder();
  498.                 if (matrix[row][col] == word.charAt(0)) {
  499.                     searchWord(matrix, word, 0, buf, row, col, -1, -1);
  500.                 }
  501.             }
  502.         }
  503.  
  504.     }
  505.  
  506.     public static void maxSubSubmatrix(int[][] mat) {
  507.         int rows = mat.length;
  508.         int cols = mat[0].length;
  509.  
  510.         int[] currentResult;
  511.         int maxSum = Integer.MIN_VALUE;
  512.         int left = 0;
  513.         int top = 0;
  514.         int right = 0;
  515.         int bottom = 0;
  516.  
  517.         for (int lefCol = 0; lefCol < cols; lefCol++) {
  518.             int temp[] = new int[rows];
  519.             for (int rightCol = lefCol; rightCol < cols; rightCol++) {
  520.                 for (int i = 0; i < rows; i++) {
  521.                     temp[i] += mat[i][rightCol];
  522.                 }
  523.                 currentResult = kadaneAlgo(temp);
  524.  
  525.                 if (currentResult[0] > maxSum) {
  526.                     currentResult[0] = maxSum;
  527.                     left = lefCol;
  528.                     top = currentResult[1];
  529.                     bottom = currentResult[2];
  530.                     right = rightCol;
  531.                 }
  532.  
  533.             }
  534.         }
  535.         System.out.println("MaxSum: " + maxSum + ", range: [(" + left + ", " + top + ")(" + right + ", " + bottom
  536.                 + ")]");
  537.  
  538.     }
  539.  
  540.     public static int[] kadaneAlgo(int[] arr) {
  541.         int[] result = new int[] { 0, -1, -1 };
  542.         int curSum = 0;
  543.         int startIndex = 0;
  544.         for (int i = 0; i < arr.length; i++) {
  545.             curSum += arr[i];
  546.             if (curSum < 0) {
  547.                 curSum = 0;
  548.                 startIndex = i + 1;
  549.             } else if (curSum > result[0]) {
  550.                 result[0] = curSum;
  551.                 result[1] = startIndex;
  552.                 result[2] = i;
  553.             }
  554.  
  555.         }
  556.         if (result[2] == -1) {
  557.             result[0] = 0;
  558.             for (int i = 0; i < arr.length; i++) {
  559.                 if (arr[i] > result[0]) {
  560.                     result[0] = arr[i];
  561.                     result[1] = i;
  562.                     result[2] = i;
  563.                 }
  564.             }
  565.         }
  566.         return result;
  567.     }
  568.  
  569. }
Add Comment
Please, Sign In to add comment