Skip to content

Commit 8e4a85a

Browse files
added FillASpecialGrid
1 parent 3b7b03c commit 8e4a85a

File tree

3 files changed

+57
-1
lines changed

3 files changed

+57
-1
lines changed

docs/recursion.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
- [Generate Parentheses](src/com/problems/recursion/GenerateAllBalancedParenthesis.java)
2929
- [Print N-bit binary numbers having more 1s than 0s](src/com/problems/recursion/GenerateNBitBinaryNumberHavingMore1sInAllPrefixes.java)
3030
- [Subarrays with Sum k](src/com/problems/recursion/SubarraysWithSumK.java)
31+
- [Fill a Special Grid](src/com/problems/recursion/FillASpecialGrid.java)
3132

3233

3334
- [Print all subsequences/Power Set with unique elements](src/com/problems/recursion/PowerSet1.java)
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.problems.recursion;
2+
3+
import com.util.PrintUtl;
4+
5+
/*
6+
* Problem links:
7+
* https://leetcode.com/problems/fill-a-special-grid/description/
8+
*
9+
* Solution link
10+
*
11+
* */
12+
public class FillASpecialGrid {
13+
public static void main(String[] args) {
14+
type1();
15+
type2();
16+
}
17+
18+
// recursive way
19+
private static void type2() {
20+
int N = 2;
21+
int[][] ans = specialGrid1(N);
22+
PrintUtl.print2D(ans);
23+
}
24+
25+
public static int[][] specialGrid1(int N) {
26+
if (N == 0) return new int[][]{new int[]{0}};
27+
int n = 1 << N;
28+
int[][] arr = new int[n][n];
29+
int low = 0, high = (1 << 2 * N) - 1;
30+
fill2(arr, low, high, 0, n - 1, 0, n - 1);
31+
return arr;
32+
}
33+
34+
private static void fill2(int[][] arr, int low, int high, int x1, int x2, int y1, int y2) {
35+
int count = high - low + 1;
36+
int d = (x2 - x1 + 1) / 2;
37+
int q = count / 4;
38+
if (count == 4) {
39+
arr[x1][y2] = low;
40+
arr[x2][y2] = low + 1;
41+
arr[x2][y1] = low + 2;
42+
arr[x1][y1] = high;
43+
} else {
44+
fill2(arr, low, low + q - 1, x1, x1 + d - 1, y1 + d, y2);
45+
fill2(arr, low + q, low + 2 * q - 1, x1 + d, x2, y1 + d, y2);
46+
fill2(arr, low + 2 * q, low + 3 * q - 1, x1 + d, x2, y1, y1 + d - 1);
47+
fill2(arr, low + 3 * q, high, x1, x1 + d - 1, y1, y1 + d - 1);
48+
}
49+
}
50+
51+
// iterative way
52+
private static void type1() {
53+
54+
}
55+
}

docs/src/com/problems/recursion/SubarraysWithSumK.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
/*
77
* Problem links:
8-
* https://www.codingninjas.com/studio/problems/subarrays-with-sum-%E2%80%98k'_6922076
8+
* https://www.naukri.com/code360/problems/subarrays-with-sum-k_6922076
99
* Solution link
1010
*
1111
* */

0 commit comments

Comments
 (0)