question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
smallest-value-after-replacing-with-sum-of-prime-factors | Sieve of Erathonesis for prime factorization | sieve-of-erathonesis-for-prime-factoriza-kkzy | Intuition\nSieve - \n\n# Approach\nUse SPF array\n\n# Complexity\n- Time complexity:\n- \nCalculation of sieve -> O(n log log n)\nStack memory for recursion (ca | hetfadia | NORMAL | 2024-11-13T10:25:38.445196+00:00 | 2024-11-13T10:25:38.445229+00:00 | 1 | false | # Intuition\nSieve - \n\n# Approach\nUse SPF array\n\n# Complexity\n- Time complexity:\n- \nCalculation of sieve -> O(n log log n)\nStack memory for recursion (can be reduced to O(1) using iterative) - O(1) considering we can convert it to iterative\n\n- Space complexity:\nStorage of sieve O(n)\n\n# Code\n```cpp []\nclass Sieve{\n const static int a3 = 100050;\n short int prime[a3 + 1];\n public:\n Sieve(int n)\n {\n for(int i=0;i<a3;i++){\n prime[i]=-1;\n }\n for (int p = 2; p * p <= n; p++)\n {\n if (prime[p] == -1)\n {\n for (int i = p * p; i <= n; i += p)\n prime[i] = p;\n }\n }\n }\n int get_min_prime_sum(int n){\n int _n = n;\n int suma=0;\n while(prime[_n]!=-1){\n suma+=prime[_n];\n _n /= prime[_n];\n }\n suma+=_n;\n if(suma<n){\n return get_min_prime_sum(suma);\n }\n return suma;\n }\n};\nSieve * s = new Sieve(100010);\nclass Solution {\npublic:\n int smallestValue(int n) {\n return s->get_min_prime_sum(n);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
smallest-value-after-replacing-with-sum-of-prime-factors | Beats 100% | beats-100-by-riyabansal_1708-zmhv | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | riyabansal_1708 | NORMAL | 2024-11-11T17:45:56.311002+00:00 | 2024-11-11T17:45:56.311036+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int smallestValue(int n) {\n while (true) {\n int sum = 0, original_n = n;\n for (int i = 2; i * i <= n; ++i) {\n while (n % i == 0) {\n sum += i;\n n /= i;\n }\n }\n if (n > 1) sum += n; \n if (sum == original_n) return sum; \n n = sum;\n }\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
smallest-value-after-replacing-with-sum-of-prime-factors | Brute force, but easy and self-explainatory solution | brute-force-but-easy-and-self-explainato-cn4q | \n\n# Code\njava []\nclass Solution {\n public int smallestValue(int n) {\n int k=n;\n if(n<=4) return n;\n while(true){\n in | atishayjain78001 | NORMAL | 2024-10-26T17:16:43.348797+00:00 | 2024-10-26T17:16:43.348834+00:00 | 0 | false | \n\n# Code\n```java []\nclass Solution {\n public int smallestValue(int n) {\n int k=n;\n if(n<=4) return n;\n while(true){\n int sum=0;\n for(int i=2;i<=n/2;i++){\n if(prime(i)){\n while(n%i==0){\n sum+=i;\n n/=i;\n }\n }\n }\n\n\n //EDGE CASES \n if(n==1) {\n sum-=1;\n }\n sum+=n;\n if(n==sum){\n k=sum;\n break;\n } else {\n n=sum;\n k=sum;\n }\n }\n return k;\n }\n private boolean prime(int n){\n for(int i=2;i<=n/2;i++){\n if(n%i==0){\n return false;\n }\n }\n return true;\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
smallest-value-after-replacing-with-sum-of-prime-factors | Easy Solution beats 99.19 % | easy-solution-beats-9919-by-gopigaurav-0qzm | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | gopigaurav | NORMAL | 2024-10-23T14:37:30.933221+00:00 | 2024-10-23T14:37:30.933247+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def smallestValue(self, n: int) -> int:\n def prime_factors(n):\n factors = []\n \n # Divide by 2 to get rid of all even factors\n while n % 2 == 0:\n factors.append(2)\n n //= 2\n \n # Try odd numbers starting from 3\n for i in range(3, int(n**0.5) + 1, 2):\n while n % i == 0:\n factors.append(i)\n n //= i\n \n # If n is still greater than 2, it must be a prime\n if n > 2:\n factors.append(n)\n \n return factors\n \n while True:\n temp = prime_factors(n) \n factor_sum = sum(temp)\n if factor_sum == n:\n break\n n = factor_sum\n \n return n\n``` | 0 | 0 | ['Python3'] | 0 |
smallest-value-after-replacing-with-sum-of-prime-factors | Runtime C# beats 100% | runtime-c-beats-100-by-cachxinhtrai-euia | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | cachxinhtrai | NORMAL | 2024-10-18T08:38:17.998352+00:00 | 2024-10-18T08:38:17.998376+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(Sqrt(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```csharp []\npublic class Solution {\n public bool IsPrime(int n)\n {\n if(n < 2) return false;\n for(int i = 2; i * i <= n; i++)\n {\n if(n % i == 0) return false;\n }\n return true;\n }\n public int DivideProduct(int n)\n {\n int totalDivideProduct = 0;\n for(int i = 2; i * i <= n; i++)\n {\n while(n%i==0) \n {\n n/=i;\n totalDivideProduct += i;\n }\n\n }\n if(n > 1) totalDivideProduct += n;\n return totalDivideProduct;\n }\n public int SmallestValue(int n) {\n HashSet<int> seen = new HashSet<int>(); // L\u01B0u c\xE1c gi\xE1 tr\u1ECB \u0111\xE3 t\xEDnh\n int result = DivideProduct(n);\n \n while(!IsPrime(result) && !seen.Contains(result)) \n {\n seen.Add(result); // Th\xEAm v\xE0o set \u0111\u1EC3 tr\xE1nh l\u1EB7p l\u1EA1i\n result = DivideProduct(result);\n }\n \n return result;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
smallest-value-after-replacing-with-sum-of-prime-factors | ❄ Easy Java Solution ❄ Beats 100% of Java Users . | easy-java-solution-beats-100-of-java-use-wjvl | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | zzzz9 | NORMAL | 2024-10-12T15:38:01.320771+00:00 | 2024-10-12T15:38:01.320793+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int sumP(int n) {\n int sum = 0;\n while (n % 2 == 0) {\n sum += 2;\n n >>= 1; \n }\n for (int i = 3; i * i <= n; i += 2) {\n while (n % i == 0) {\n sum += i;\n n /= i;\n }\n }\n\n if (n > 1) {\n sum += n;\n }\n return sum;\n }\n\n public int smallestValue(int n) {\n int k = 0;\n while (true) {\n k = sumP(n);\n if (n == k) {\n return n;\n }\n n = k;\n }\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
smallest-value-after-replacing-with-sum-of-prime-factors | Iterative Prime Factor Summation for Number Reduction | iterative-prime-factor-summation-for-num-qx4o | Intuition\nThe problem seems to involve repeatedly summing the prime factors of a number until the sum remains unchanged. This suggests a process of reducing th | idriss55 | NORMAL | 2024-09-21T10:44:43.140581+00:00 | 2024-09-21T10:44:43.140612+00:00 | 4 | false | # Intuition\nThe problem seems to involve repeatedly summing the prime factors of a number until the sum remains unchanged. This suggests a process of reducing the number by its prime factors iteratively.\n\n# Approach\n- Prime Factorization: Create a function PrimeFactors that calculates the sum of all prime factors of a given number n.\n* Iterative Reduction: Use the PrimeFactors function in another function smallestValue to iteratively reduce the number until the sum of its prime factors equals the number itself.\n# Complexity\n\n- Time complexity: The time complexity for finding prime factors of a number n is approximately O(sqrt(n)\u200B). Since we are iterating this process until the number stabilizes, the overall time complexity can be considered as O(k\u22C5sqrt(n)\u200B), where k is the number of iterations.\n- Space complexity: The space complexity is O(1)\n as we are using a constant amount of extra space.\n# Code\n```cpp []\nclass Solution {\npublic:\n int PrimeFactors(int n) {\n int sum = 0;\n while (n % 2 == 0) {\n sum += 2;\n n /= 2;\n }\n for (int i = 3; i <= sqrt(n); i += 2) {\n while (n % i == 0) {\n sum += i;\n n /= i;\n }\n }\n if (n > 2) {\n sum += n;\n }\n return sum;\n }\n\n int smallestValue(int n) {\n int sum;\n while (true) {\n sum = PrimeFactors(n);\n if (sum == n) {\n return sum;\n } else {\n n = sum;\n }\n }\n return n; \n }\n};\n\n``` | 0 | 0 | ['Math', 'Number Theory', 'C++'] | 0 |
queens-that-can-attack-the-king | [Python] Check 8 steps in 8 Directions | python-check-8-steps-in-8-directions-by-twnxc | Explanation\nStart from the position of king,\nwe try to find a queen in 8 directions.\nI didn\'t bother skipping the case where (i,j) = (0,0)\n\n\n## Complexit | lee215 | NORMAL | 2019-10-13T04:07:33.715319+00:00 | 2019-10-14T12:40:16.712705+00:00 | 11,159 | false | ## **Explanation**\nStart from the position of king,\nwe try to find a queen in 8 directions.\nI didn\'t bother skipping the case where `(i,j) = (0,0)`\n<br>\n\n## **Complexity**\nTime `O(1)`, Space `O(1)`\nas the size of chessboard is limited.\n\nFor the chessboard of `N * N`\nTime `O(queens + 8N)`\nSpace `O(queens)`\n<br>\n\n**Python:**\n```python\n def queensAttacktheKing(self, queens, king):\n res = []\n queens = {(i, j) for i, j in queens}\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n for k in xrange(1, 8):\n x, y = king[0] + i * k, king[1] + j * k\n if (x, y) in queens:\n res.append([x, y])\n break\n return res\n```\n | 160 | 5 | [] | 32 |
queens-that-can-attack-the-king | C++ Tracing | c-tracing-by-votrubac-s4xh | Trace in all directions from the king until you hit a queen or go off the board. Since the board is limited to 8 x 8, we can use a boolean matrix to lookup quee | votrubac | NORMAL | 2019-10-13T04:34:23.632643+00:00 | 2019-10-13T04:38:10.192156+00:00 | 5,049 | false | Trace in all directions from the king until you hit a queen or go off the board. Since the board is limited to `8 x 8`, we can use a boolean matrix to lookup queen positions; we could use a hash map for a larger board.\n```\nvector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& k) {\n bool b[8][8] = {};\n for (auto& q : queens) b[q[0]][q[1]] = true;\n vector<vector<int>> res;\n for (auto i = -1; i <= 1; ++i)\n for (auto j = -1; j <= 1; ++j) {\n if (i == 0 && j == 0) continue;\n auto x = k[0] + i, y = k[1] + j;\n while (min(x, y) >= 0 && max(x, y) < 8) {\n if (b[x][y]) {\n res.push_back({ x, y });\n break;\n }\n x += i, y += j;\n }\n }\n return res;\n}\n``` | 104 | 1 | [] | 9 |
queens-that-can-attack-the-king | Java short and concise beat 100% | java-short-and-concise-beat-100-by-wall_-u3ic | Start from King and reach to the Queens on 8 directions. Break on that direction if one queen is found.\n\nclass Solution {\n public List<List<Integer>> quee | wall__e | NORMAL | 2019-10-13T04:10:19.810221+00:00 | 2019-10-13T04:13:56.638496+00:00 | 5,420 | false | Start from King and reach to the Queens on 8 directions. Break on that direction if one queen is found.\n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n boolean[][] seen = new boolean[8][8];\n for (int[] queen : queens) seen[queen[0]][queen[1]] = true;\n int[] dirs = {-1, 0, 1};\n for (int dx : dirs) {\n for (int dy : dirs) {\n if (dx == 0 && dy == 0) continue;\n int x = king[0], y = king[1];\n while (x + dx >= 0 && x + dx < 8 && y + dy >= 0 && y + dy < 8) {\n x += dx;\n y += dy;\n if (seen[x][y]) {\n result.add(Arrays.asList(x, y));\n break;\n }\n }\n }\n }\n return result;\n } \n}\n``` | 67 | 2 | [] | 12 |
queens-that-can-attack-the-king | Java - 0 ms , faster than 100% , Easy to understand solution | java-0-ms-faster-than-100-easy-to-unders-4mm0 | The basic idea here is to move to all the 8 possible directions from king and see if any of the spot is occupied by a queen. If occupied then add that position | anand004 | NORMAL | 2020-11-05T08:59:30.753401+00:00 | 2020-11-05T08:59:30.753434+00:00 | 1,478 | false | The basic idea here is to move to all the 8 possible directions from king and see if any of the spot is occupied by a queen. If occupied then add that position to output and don\'t move in that direction since all other queens in that direction will be blocked by this queen.\n\n\n\n\n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n boolean[][] q = new boolean[8][8];\n\t\t//Mark all the positions of queen on a 8 X 8 board.\n for (int[] queen: queens) {\n q[queen[0]][queen[1]] = true;\n }\n List<List<Integer>> output = new ArrayList<>();\n\t\t//Specify all the moves of the queen\n int[][] moves = {{-1,-1}, {0,-1}, {1,-1},{1,0}, {1,1}, {0,1}, {-1,1}, {-1,0}};\n for(int i = 0; i < moves.length; i++){\n int k = king[0] + moves[i][0];\n int l = king[1] + moves[i][1];\n while(k >= 0 && l >=0 && k < 8 && l < 8){\n if(q[k][l]){\n List<Integer> pair = new ArrayList<>();\n pair.add(k);\n pair.add(l);\n output.add(pair);\n break;\n }\n k = k + moves[i][0];\n l = l + moves[i][1];\n }\n }\n \n return output;\n }\n}\n\n``` | 20 | 0 | ['Java'] | 3 |
queens-that-can-attack-the-king | Traverse From King | traverse-from-king-by-yuyingji-e0sm | \ngrid = [[0 for _ in range(8)] for _ in range(8)]\n res = []\n for q in queens:\n grid[q[0]][q[1]] = 1\n x = king[0]\n y | yuyingji | NORMAL | 2019-10-13T04:14:57.379647+00:00 | 2019-10-13T04:15:30.360267+00:00 | 1,943 | false | ```\ngrid = [[0 for _ in range(8)] for _ in range(8)]\n res = []\n for q in queens:\n grid[q[0]][q[1]] = 1\n x = king[0]\n y = king[1]\n dir = [(1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1), (0, 1), (0, -1)]\n for i in range(1, 8):\n level = []\n for d in dir:\n a = x + d[0] * i\n b = y + d[1] * i\n print(a,b)\n if 0 <= a < 8 and 0 <= b < 8 and grid[a][b] == 1:\n res.append([a, b])\n else:\n level.append(d)\n dir = level\n return res\n\t``` | 12 | 0 | [] | 3 |
queens-that-can-attack-the-king | [Java/C++] Check 8 directions from King, Clean code, 0 ms beat 100% | javac-check-8-directions-from-king-clean-to74 | Java\njava\npublic class Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new | hiepit | NORMAL | 2019-10-13T04:05:13.678999+00:00 | 2019-10-13T06:30:38.946624+00:00 | 2,311 | false | **Java**\n```java\npublic class Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n boolean[][] seen = new boolean[8][8];\n for (int[] queen : queens) seen[queen[0]][queen[1]] = true;\n\n for (int dr = -1; dr <= 1; dr++) { // find the nearest queen can attack king by 8 directions\n for (int dc = -1; dc <= 1; dc++) {\n if (dr == 0 && dc == 0) continue; // exclude center\n List<Integer> queen = findNearestQueenCanAttackKing(seen, king, dr, dc);\n if (queen != null) result.add(queen);\n }\n }\n return result;\n }\n\n private List<Integer> findNearestQueenCanAttackKing(boolean[][] seen, int[] king, int dr, int dc) {\n int r = king[0] + dr, c = king[1] + dc;\n while (r >= 0 && c >= 0 && r < 8 && c < 8) {\n if (seen[r][c]) return Arrays.asList(r, c);\n r += dr;\n c += dc;\n }\n return null;\n }\n}\n```\n\n**C++**\n```C++\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> result;\n bool seen[8][8] = {};\n for (vector<int> queen : queens) seen[queen[0]][queen[1]] = true;\n\n for (int dr = -1; dr <= 1; dr++) { // find the nearest queen can attack king by 8 directions\n for (int dc = -1; dc <= 1; dc++) {\n if (dr == 0 && dc == 0) continue; // exclude center\n vector<int> queen = findNearestQueenCanAttackKing(seen, king, dr, dc);\n if (queen.size() > 0) result.push_back(queen);\n }\n }\n return result;\n }\n \n vector<int> findNearestQueenCanAttackKing(bool seen[8][8], vector<int>& king, int dr, int dc) {\n int r = king[0] + dr, c = king[1] + dc;\n while (r >= 0 && c >= 0 && r < 8 && c < 8) {\n if (seen[r][c]) return vector<int>{r, c};\n r += dr;\n c += dc;\n }\n return vector<int>{};\n }\n};\n```\n\n**Complexity**\n- Time: O(N + 8\\*8), N <= 63\n- Splace: O(64), for seen array | 12 | 0 | [] | 2 |
queens-that-can-attack-the-king | C++ Naïve Solution | c-naive-solution-by-chirags_30-o9d3 | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n vector<vector<int> | chirags_30 | NORMAL | 2021-05-16T06:00:24.395921+00:00 | 2021-05-16T06:00:24.395963+00:00 | 1,182 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n vector<vector<int>> ans;\n \n map<pair<int, int>, bool>M;\n \n for(auto q:queens)\n M[{q[0], q[1]}] = true; \n \n int kr = king[0], kc = king[1];\n \n // top\n for(int r=kr; r>=0; r--)\n {\n if(M.find({r , kc}) != M.end())\n {\n ans.push_back({r, kc});\n break;\n }\n }\n \n // down\n for(int r=kr; r<8; r++)\n {\n if(M.find({r , kc}) != M.end())\n {\n ans.push_back({r, kc});\n break;\n }\n }\n \n // left\n for(int c=kc; c>=0; c--)\n {\n if(M.find({kr , c}) != M.end())\n {\n ans.push_back({kr, c});\n break;\n }\n }\n \n // right\n for(int c=kc; c<8; c++)\n {\n if(M.find({kr , c}) != M.end())\n {\n ans.push_back({kr, c});\n break;\n }\n }\n \n // top left\n int c = kc;\n for(int r=kr; r>=0 and c>=0; r--)\n {\n if(M.find({r , c}) != M.end())\n {\n ans.push_back({r, c});\n break;\n }\n c--;\n }\n \n // top right\n for(int r=kr, c = kc; r>=0 and c<8; r--, c++)\n {\n if(M.find({r , c}) != M.end())\n {\n ans.push_back({r, c});\n break;\n }\n }\n \n // bottom left\n for(int r=kr, c=kc; r<8 and c>=0; r++, c--)\n {\n if(M.find({r , c}) != M.end())\n {\n ans.push_back({r, c});\n break;\n }\n }\n \n // bottom right\n for(int r=kr, c=kc; r<8 and c<8; r++, c++)\n {\n if(M.find({r , c}) != M.end())\n {\n ans.push_back({r, c});\n break;\n }\n }\n \n return ans;\n }\n};\n``` | 10 | 0 | ['C', 'C++'] | 0 |
queens-that-can-attack-the-king | Simple Python Solution | simple-python-solution-by-whissely-lx6v | \nclass Solution:\n # Time: O(1)\n # Space: O(1)\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n | whissely | NORMAL | 2020-08-14T05:13:43.850963+00:00 | 2020-08-14T05:13:43.850998+00:00 | 811 | false | ```\nclass Solution:\n # Time: O(1)\n # Space: O(1)\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n queen_set = {(i, j) for i, j in queens}\n res = []\n \n for dx, dy in [[0, 1], [1, 0], [-1, 0], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]]:\n x, y = king[0], king[1]\n while 0 <= x < 8 and 0 <= y < 8:\n x += dx\n y += dy\n if (x, y) in queen_set:\n res.append([x, y])\n break\n return res\n``` | 10 | 0 | ['Python', 'Python3'] | 3 |
queens-that-can-attack-the-king | [Java] Solution for simple folks like me | java-solution-for-simple-folks-like-me-b-24dn | \n// Time: O(1)\n// Space: O(1)\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> | djl218 | NORMAL | 2021-05-26T21:09:17.690446+00:00 | 2021-05-26T21:09:17.690494+00:00 | 476 | false | ```\n// Time: O(1)\n// Space: O(1)\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> attackQueens = new ArrayList<>();\n char[][] grid = new char[8][8];\n for (int[] queen : queens) {\n grid[queen[0]][queen[1]] = \'Q\';\n }\n \n // Go down\n for (int i = king[0]; i < 8; i++) {\n if (grid[i][king[1]] == \'Q\') {\n attackQueens.add(List.of(i, king[1]));\n break;\n }\n }\n \n // Go up\n for (int i = king[0]; i >= 0; i--) {\n if (grid[i][king[1]] == \'Q\') {\n attackQueens.add(List.of(i, king[1]));\n break;\n }\n }\n \n // Go right\n for (int i = king[1]; i < 8; i++) {\n if (grid[king[0]][i] == \'Q\') {\n attackQueens.add(List.of(king[0], i));\n break;\n }\n }\n \n // Go left\n for (int i = king[1]; i >= 0; i--) {\n if (grid[king[0]][i] == \'Q\') {\n attackQueens.add(List.of(king[0], i));\n break;\n }\n }\n \n // Up left diagonal\n for (int i = king[0], j = king[1]; i >= 0 && j >= 0; i--, j--) {\n if (grid[i][j] == \'Q\') {\n attackQueens.add(List.of(i, j));\n break;\n }\n }\n \n // Up right diagonal\n for (int i = king[0], j = king[1]; i >= 0 && j < 8; i--, j++) {\n if (grid[i][j] == \'Q\') {\n attackQueens.add(List.of(i, j));\n break;\n }\n }\n \n // Down left diagonal\n for (int i = king[0], j = king[1]; i < 8 && j >= 0; i++, j--) {\n if (grid[i][j] == \'Q\') {\n attackQueens.add(List.of(i, j));\n break;\n }\n }\n \n // Down right diagonal\n for (int i = king[0], j = king[1]; i < 8 && j < 8; i++, j++) {\n if (grid[i][j] == \'Q\') {\n attackQueens.add(List.of(i, j));\n break;\n }\n }\n \n return attackQueens;\n }\n}\n``` | 9 | 0 | [] | 3 |
queens-that-can-attack-the-king | Java start from king's position and check 8 directions | java-start-from-kings-position-and-check-5l5d | \nclass Solution {\n \n int[][] directions = {{0,1}, {1,0}, {0,-1}, {-1,0}, {1,1}, {-1,-1}, {1,-1}, {-1,1}};\n \n public List<List<Integer>> queensA | user3600w | NORMAL | 2021-06-19T06:26:39.827764+00:00 | 2021-06-19T06:26:39.827813+00:00 | 570 | false | ```\nclass Solution {\n \n int[][] directions = {{0,1}, {1,0}, {0,-1}, {-1,0}, {1,1}, {-1,-1}, {1,-1}, {-1,1}};\n \n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int[][] board = new int[8][8];\n List<List<Integer>> res = new LinkedList<>();\n \n for(int[] queenPos : queens){\n board[queenPos[0]][queenPos[1]] = 1;\n }\n \n for(int[] direction : directions){\n int row = king[0], col = king[1];\n \n while(row>=0 && row<8 && col>=0 && col<8 && board[row][col]==0){\n row += direction[0];\n col += direction[1];\n }\n \n if(row>=0 && row<8 && col>=0 && col<8){\n res.add(new LinkedList<>(Arrays.asList(new Integer[]{row, col})));\n }\n }\n \n return res;\n }\n}\n``` | 7 | 0 | ['Java'] | 1 |
queens-that-can-attack-the-king | [Python 3/Java] check 8 directions, with explanation and analys. | python-3java-check-8-directions-with-exp-2uij | Start from king, for each direction in the 8 ones, move 1 step each time till find a queen or out of bound.\n\n\n\nTime and Space Complexity\n~~~O(64)~~~\nTime: | wustl | NORMAL | 2019-10-13T07:44:43.557817+00:00 | 2023-04-25T13:10:51.086921+00:00 | 1,015 | false | Start from king, for each direction in the 8 ones, move 1 step each time till find a queen or out of bound.\n<iframe src="https://leetcode.com/playground/Ydxfqc7c/shared" frameBorder="0" width="800" height="400"></iframe>\n\n\n**Time and Space Complexity**\n~~~O(64)~~~\nTime: `O(n * n + Q)`, space: `O(Q)`, where `n = 8` is the size of the chess board, and `Q = queen.length` is the size of the `queen`. | 6 | 0 | ['Java', 'Python3'] | 2 |
queens-that-can-attack-the-king | C++ | Checking in all 8 directions | c-checking-in-all-8-directions-by-adiroc-sd8k | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>>ans;\n | adirocks1309 | NORMAL | 2022-01-28T05:54:02.634718+00:00 | 2022-01-28T05:54:02.634765+00:00 | 592 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>>ans;\n vector<vector<int>>seen(8,vector<int>(8,0));\n for(auto queen:queens){\n seen[queen[0]][queen[1]]=1;\n }\n for(int dx=-1;dx<=1;dx++){\n for(int dy=-1;dy<=1;dy++){\n if(dx==0 && dy==0){\n continue;\n }\n int x=king[0];\n int y=king[1];\n \n while(x+dx>=0 && y+dy>=0 && x+dx<8 && y+dy<8){\n x+=dx;\n y+=dy;\n if(seen[x][y]){\n ans.push_back({x,y});\n break; // ones we got a queen in our current path we will stop\n }\n }\n }\n }\n return ans;\n }\n};\n```\n#### **If you understood the solution please upvote :)** | 5 | 0 | ['C', 'C++'] | 1 |
queens-that-can-attack-the-king | [Python3] 2 approaches | python3-2-approaches-by-ye15-500r | \n\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans = []\n x, y = king\n | ye15 | NORMAL | 2021-03-02T23:03:56.420996+00:00 | 2021-03-02T23:03:56.421029+00:00 | 279 | false | \n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans = []\n x, y = king\n queens = {(x, y) for x, y in queens}\n for dx in (-1, 0, 1):\n for dy in (-1, 0, 1):\n for k in range(1, 8):\n xx, yy = x+k*dx, y+k*dy\n if (xx, yy) in queens: \n ans.append([xx, yy])\n break \n return ans \n```\n\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans = [[inf]*2 for _ in range(8)]\n xx, yy = king\n fn = lambda x: max(abs(x[0]-xx), abs(x[1]-yy))\n for x, y in queens: \n if x == xx: # same row \n if y < yy: ans[0] = min(ans[0], (x, y), key=fn)\n else: ans[1] = min(ans[1], (x, y), key=fn)\n elif yy == y: # same column\n if x < xx: ans[2] = min(ans[2], (x, y), key=fn)\n else: ans[3] = min(ans[3], (x, y), key=fn)\n elif xx-yy == x-y: # same diagonoal\n if x < xx: ans[4] = min(ans[4], (x, y), key=fn)\n else: ans[5] = min(ans[5], (x, y), key=fn)\n elif xx+yy == x+y: # same anti-diagonal\n if x < xx: ans[6] = min(ans[6], (x, y), key=fn)\n else: ans[7] = min(ans[7], (x, y), key=fn)\n \n return [[x, y] for x, y in ans if x < inf]\n``` | 5 | 0 | ['Python3'] | 1 |
queens-that-can-attack-the-king | easy | easy-by-realyogendra-9jh8 | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n vector<vector<int> | realyogendra | NORMAL | 2021-12-09T10:35:47.927444+00:00 | 2021-12-09T10:36:53.561311+00:00 | 375 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n vector<vector<int>> board(8,vector<int>(8,0)) ;\n \n for(int i=0;i<queens.size();i++) board[queens[i][0]][queens[i][1]]=1;\n \n vector<vector<int>> ans;\n for(int i=-1;i<=1;i++){\n for(int j=-1;j<=1;j++){\n if(i==0&&j==0) continue;\n int posi=king[0], posj=king[1];\n \n while(0<=posi&&posi<8&&0<=posj&&posj<8){\n if(board[posi][posj]) {ans.push_back({posi,posj}); break;}\n posi=posi+i;\n posj=posj+j;\n \n }\n }\n }\n return ans;\n \n }\n};\n``` | 4 | 0 | ['C'] | 1 |
queens-that-can-attack-the-king | java easy 100 ms solution well commented | java-easy-100-ms-solution-well-commented-24ot | \nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n //----------------------------------\n List | arshad_01 | NORMAL | 2021-04-04T10:38:06.433110+00:00 | 2021-04-04T10:40:29.195783+00:00 | 220 | false | ```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n //----------------------------------\n List<List<Integer>> list=new ArrayList<>();\n int king_x=king[0];\n int king_y=king[1];\n int[][] chess=new int[8][8];\n chess[king_x][king_y]=1;// identifier of king is one\n for(int i=0;i<queens.length;i++){\n int x=queens[i][0];\n int y=queens[i][1];\n // identifier of queen is -1\n chess[x][y]=-1;\n \n }\n \n \n //------------------------------\n // lets check in row( left side of king)\n for(int i=king_y;i>=0;i--){\n List<Integer> l=new ArrayList<>();\n if(chess[king_x][i]==-1){\n l.add(king_x);\n l.add(i);\n list.add(l);\n break;\n }\n }\n // lets check in row (right side of king)\n for(int i=king_y;i<chess[0].length;i++){\n List<Integer> l=new ArrayList<>();\n if(chess[king_x][i]==-1){\n l.add(king_x);\n l.add(i);\n list.add(l);\n break;\n }\n }\n \n // lets look in the column up to the king\n for(int i=king_x;i>=0;i--){\n List<Integer> l=new ArrayList<>();\n if(chess[i][king_y]==-1){\n l.add(i);\n l.add(king_y);\n list.add(l);\n break;\n \n }\n \n }\n //lets look for in the column down to the king\n for(int j=king_x;j<chess.length;j++){\n List<Integer> l=new ArrayList<>();\n if(chess[j][king_y]==-1){\n l.add(j);\n l.add(king_y);\n list.add(l);\n break;\n \n }\n }\n //------- lets check in diagonal\n // looking up diagonal to the king\n for(int i=king_x,j=king_y;i>=0 && j>=0;i--,j--){\n List<Integer> l=new ArrayList<>();\n if(chess[i][j]==-1){\n l.add(i);\n l.add(j);\n list.add(l);\n break;\n }\n }\n \n \n //looking down diagonal to the king \n for(int i=king_x,j=king_y;i<chess.length && j<chess[0].length;i++,j++){\n List<Integer> l=new ArrayList<>();\n if(chess[i][j]==-1){\n l.add(i);\n l.add(j);\n list.add(l);\n break;\n }\n }\n \n // looking for secondry up_diagonal\n for(int i=king_x,j=king_y;i>=0 && j<chess[0].length;i--,j++){\n List<Integer> l=new ArrayList<>();\n if(chess[i][j]==-1){\n l.add(i);\n l.add(j);\n list.add(l);\n break;\n }\n }\n //---------------------looking for secondry down diagonal\n for(int i=king_x,j=king_y;i<chess.length && j>=0;i++,j--){\n List<Integer> l=new ArrayList<>();\n if(chess[i][j]==-1){\n l.add(i);\n l.add(j);\n list.add(l);\n break;\n }\n }\n \n \n\n return list;\n }\n \n \n}\n// do upvote if you like it\n``` | 4 | 1 | ['Java'] | 0 |
queens-that-can-attack-the-king | C++ with comments | c-with-comments-by-anandman03-8e3d | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) \n {\n vector<vector<int>> an | anandman03 | NORMAL | 2020-11-11T09:05:35.513793+00:00 | 2020-11-11T09:05:35.513842+00:00 | 397 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) \n {\n vector<vector<int>> ans;\n \n // make a grid to track position of queens.\n vector<vector<bool>> grid(8, vector<bool>(8, false));\n for(auto v: queens)\n {\n grid[v[0]][v[1]] = true; //place queen\n }\n \n // SAME ROW\n // check queens in same row towards right.\n for(int j = king[1] + 1 ; j < 8 ; j++) {\n if(grid[king[0]][j] == true) {\n ans.push_back({king[0], j});\n break;\n }\n }\n // check queens in same row towards left.\n for(int j = king[1] - 1 ; j >= 0 ; j--) {\n if(grid[king[0]][j] == true) {\n ans.push_back({king[0], j});\n break;\n }\n }\n \n // SAME COLUMN\n // check queens in same col towards down.\n for(int i = king[0] + 1 ; i < 8 ; i++) {\n if(grid[i][king[1]] == true) {\n ans.push_back({i, king[1]});\n break;\n }\n }\n // check queens in same col towards up.\n for(int i = king[0] - 1 ; i >= 0 ; i--) {\n if(grid[i][king[1]] == true) {\n ans.push_back({i, king[1]});\n break;\n }\n }\n \n // CHECK DIAGONALS\n // towards top left\n for(int i = king[0], j = king[1] ; i >= 0 && j >= 0 ; i--, j--) {\n if(grid[i][j] == true) {\n ans.push_back({i, j});\n break;\n }\n }\n // towards top right\n for(int i = king[0], j = king[1] ; i >= 0 && j < 8 ; i--, j++) {\n if(grid[i][j] == true) {\n ans.push_back({i, j});\n break;\n }\n }\n // towards bottom left\n for(int i = king[0], j = king[1] ; i < 8 && j >= 0 ; i++, j--) {\n if(grid[i][j] == true) {\n ans.push_back({i, j});\n break;\n }\n }\n // towards bottom right\n for(int i = king[0], j = king[1] ; i < 8 && j < 8 ; i++, j++) {\n if(grid[i][j] == true) {\n ans.push_back({i, j});\n break;\n }\n }\n \n return ans;\n }\n};\n``` | 4 | 0 | ['C'] | 0 |
queens-that-can-attack-the-king | JAVA 85% fast, 2ms, explanation with code | java-85-fast-2ms-explanation-with-code-b-1zbc | If you found the solution helpful, kindly upvote. :)\n\n\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n | anjali100btcse17 | NORMAL | 2020-07-19T10:23:22.065136+00:00 | 2020-07-19T10:23:22.065185+00:00 | 275 | false | If you found the solution helpful, kindly upvote. :)\n\n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n \tList<List<Integer>> res= new ArrayList<List<Integer>>();\n \t//This array will store all the possible positions of the queen\n \tboolean[][] seen= new boolean[8][8]; \n \tfor(int[] q:queens)\n {\tseen[q[0]][q[1]]=true; }\n \t\n \t//Now we make a direction array\n \tint[] direction= {-1,0,1};\n \t\n \tfor(int dx:direction)\n \t{\n \t\tfor(int dy:direction)\n \t\t{\n \t\t\t//These 2 loops ensure that all the possible directions are covered\n \t\t\tif(dx==00 && dy==0) continue;\n \t\t\t//Now, we will take the coords of the king and do sort of a BFS\n \t\t\t\n \t\t\tint x=king[0];\n \t\t\tint y=king[1];\n \t\t\t\n \t\t\twhile(x+dx >=0 && x+dx<=7 && y+dy >=0 && y+dy<=7)\n \t\t\t{\n \t\t\t\tx+=dx; y+=dy;\n \t\t\t\t//Now we will check if the updated coordinates have the queen or not\n \t\t\t\tif(seen[x][y])\n \t\t\t\t{\n \t\t\t\t\tres.add(Arrays.asList(x,y));\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n \treturn res;\n }\n}\n``` | 4 | 0 | [] | 1 |
queens-that-can-attack-the-king | Python, easy to read/understand, constant space/time | python-easy-to-readunderstand-constant-s-jdqb | There were already many constant space/time solutions in Python already, but I felt that many of them were hard to read despite being written in python, which i | from81 | NORMAL | 2020-07-17T04:20:22.488785+00:00 | 2020-07-17T04:21:49.229590+00:00 | 211 | false | There were already many constant space/time solutions in Python already, but I felt that many of them were hard to read despite being written in python, which is why I decided to post my solution.\n\n1. Convert `queens` to a set. This way we can check if a queen exists at (x, y) in O(1) space.\n2. I wrote the 8 steps that can be taken in different directions from the position of the `king`.\n3. For each direction, start from the location of `king` and walk outwards until a `queen` is found.\n\n\n```python\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n queens = set([(x, y) for x, y in queens])\n directions = [\n (1, 0), (-1, 0), (0, 1), (0, -1),\n (1, 1), (-1, -1), (1, -1), (-1, 1)\n ]\n check = []\n\n for dx, dy in directions:\n x, y = king\n while 0 <= x < 8 and 0 <= y < 8 and (x, y) not in queens:\n x += dx\n y += dy\n\n if (x, y) in queens:\n check += (x, y),\n\n return check\n``` | 4 | 0 | [] | 0 |
queens-that-can-attack-the-king | cpp solution | cpp-solution-by-_mrbing-ro3d | Runtime: 8 ms, faster than 80.00% of C++ online submissions for Queens That Can Attack the King.\nMemory Usage: 11.2 MB, less than 55.09% of C++ online submissi | _mrbing | NORMAL | 2020-07-01T09:58:34.956916+00:00 | 2020-07-01T09:58:53.995413+00:00 | 195 | false | Runtime: 8 ms, faster than 80.00% of C++ online submissions for Queens That Can Attack the King.\nMemory Usage: 11.2 MB, less than 55.09% of C++ online submissions for Queens That Can Attack the King.\n```\nclass Solution {\n //keep moving in same direction and store the first queen encountered(if)\n void helper(vector<vector<int>>& queens,int i, int j, int inc_i, int inc_j, vector<vector<int>>& output){\n if( i < 0 || j < 0 || i >= 8 || j >= 8 ) return ;\n if(queens[i][j] == 1){\n output.push_back({i,j});\n return;\n }//keep moving in same direction\n helper(queens,i+inc_i,j+inc_j,inc_i,inc_j,output);\n }\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> graph(8,vector<int>(8,0));\n vector<vector<int>> output;\n int i, j;\n for(i = 0; i < queens.size(); i++){\n graph[queens[i][0]][queens[i][1]] = 1;//denoting queen\n }\n vector<int> moveX={-1,-1,-1,0,1,1,1,0};\n vector<int> moveY={-1,0,1,1,1,0,-1,-1};\n for(int i = 0; i < 8; i++){ \n helper(graph, king[0]+moveX[i], king[1]+moveY[i], moveX[i], moveY[i], output);\n }\n \n return output;\n }\n}; | 4 | 0 | [] | 0 |
queens-that-can-attack-the-king | Java beat 100% DFS solution | java-beat-100-dfs-solution-by-raddix-04e4 | Here, we just need to go in all the 8 directions and if we encounter the queen, add them to the\nanswer.\n\n\tclass Solution {\n\t\tpublic List> queensAttackthe | raddix | NORMAL | 2020-06-26T12:28:24.323174+00:00 | 2020-06-26T12:28:24.323212+00:00 | 348 | false | Here, we just need to go in all the 8 directions and if we encounter the queen, add them to the\nanswer.\n\n\tclass Solution {\n\t\tpublic List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n \n\t\t//List that will contain our answer\n List<List<Integer>> ans = new ArrayList<>();\n \n\t\t//All 8 direction\n int[][] dir = {{-1,0},{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1}};\n \n\t\t//Board that will help us in identifying the location of queen\n boolean[][] board = new boolean[8][8];\n \n\t\t//Identify the queens on board\n for(int[] a : queens)\n board[a[0]][a[1]] = true;\n \n //Go in every direction \n for(int[] a : dir){\n int[] temp = new int[]{king[0]+a[0],king[1]+a[1]};\n dfs(ans,board,temp,a);\n }\n return ans;\n }\n \n private void dfs(List<List<Integer>> ans, boolean[][] board, int[] curr, int[] dir){\n\t\t//Base checks\n if(curr[0]<0 || curr[0]>=8)\n return;\n \n if(curr[1]<0 || curr[1]>=8)\n return;\n \n\t\t//If we found a queen then no needs to go further\n if(board[curr[0]][curr[1]]){\n List<Integer> temp = new ArrayList<>();\n temp.add(curr[0]);\n temp.add(curr[1]);\n ans.add(temp);\n return;\n }\n \n curr[0] += dir[0];\n curr[1] += dir[1];\n \n dfs(ans,board,curr,dir);\n }\n} | 4 | 0 | ['Depth-First Search', 'Java'] | 0 |
queens-that-can-attack-the-king | javascript 52ms | javascript-52ms-by-itoi06-bbd6 | \n/**\n * @param {number[][]} queens\n * @param {number[]} king\n * @return {number[][]}\n */\nvar queensAttacktheKing = function(queens, king) {\n \n let | itoi06 | NORMAL | 2020-03-29T09:59:59.010704+00:00 | 2020-03-29T09:59:59.010754+00:00 | 137 | false | ```\n/**\n * @param {number[][]} queens\n * @param {number[]} king\n * @return {number[][]}\n */\nvar queensAttacktheKing = function(queens, king) {\n \n let answer = [];\n \n traverse(king[0],king[1],-1,-1);\n traverse(king[0],king[1],-1,0);\n traverse(king[0],king[1],-1,1);\n traverse(king[0],king[1],0,-1);\n traverse(king[0],king[1],0,1);\n traverse(king[0],king[1],1,-1);\n traverse(king[0],king[1],1,0);\n traverse(king[0],king[1],1,1);\n \n return answer;\n \n function traverse(currentX, currentY, x, y) {\n if (currentX < 0 || currentY < 0 || currentX > 7 || currentY > 7) return null;\n for (let i = 0; i < queens.length; i++) {\n if (currentX == queens[i][0] && currentY == queens[i][1]) {\n answer.push([currentX,currentY])\n return null;\n }\n }\n traverse(currentX + x, currentY + y, x, y);\n }\n};\n``` | 4 | 0 | [] | 0 |
queens-that-can-attack-the-king | 0ms C++ code with explaination | 0ms-c-code-with-explaination-by-thisisno-m62h | The point to be noted here is that there are at max 8 possible attackers (for 8 directions) \nWe denote directions using this matrix:\n\n0 1 2\n3 Kin | thisisnotme123 | NORMAL | 2019-10-13T13:11:53.472411+00:00 | 2019-10-13T13:11:53.472460+00:00 | 260 | false | The point to be noted here is that there are at max 8 possible attackers (for 8 directions) \nWe denote directions using this matrix:\n\n0 1 2\n3 King 4\n5 6 7\n\nNow for iterate on all the queens and check if it can attack the king, if yes then from which direction, if no previous queen is attacking from that direction, then we assign current queen to attack king from this direction, else we choose the queen with minimum distance from current queen and the previously assigned queen.\n\n```\nclass Solution {\n int dis(vector<int>ans,vector<int>attacker){\n return abs(ans[0]-attacker[0])+abs(ans[1]-attacker[1]);\n }\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int> >sol;\n vector< vector<int> > attackers(8);\n for(int i=0;i<queens.size();i++){\n if(king[0]==queens[i][0]&&king[1]>queens[i][1]){\n if((attackers[3].size()==0)||(dis(attackers[3],king)>dis(queens[i],king)))\n attackers[3]=queens[i];\n }\n if(king[0]==queens[i][0]&&king[1]<queens[i][1]){\n if((attackers[4].size()==0)||(dis(attackers[4],king)>dis(queens[i],king)))\n attackers[4]=queens[i];\n }\n if(king[0]-queens[i][0]==king[1]-queens[i][1]&&king[0]>queens[i][0]){\n if((attackers[0].size()==0)||(dis(attackers[0],king)>dis(queens[i],king)))\n attackers[0]=queens[i];\n \n }\n if(king[0]-queens[i][0]==king[1]-queens[i][1]&&king[0]<queens[i][0]){\n if((attackers[7].size()==0)||(dis(attackers[7],king)>dis(queens[i],king)))\n attackers[7]=queens[i];\n }\n if(king[1]-queens[i][1]==0 &&king[0]>queens[i][0]){\n if((attackers[1].size()==0)||(dis(attackers[1],king)>dis(queens[i],king)))\n attackers[1]=queens[i];\n }\n if(king[1]-queens[i][1]==0 &&king[0]<queens[i][0]){\n if((attackers[6].size()==0)||(dis(attackers[6],king)>dis(queens[i],king)))\n attackers[6]=queens[i];\n }\n if(king[0]-queens[i][0]==-(king[1]-queens[i][1])&&king[0]>queens[i][0]){\n if((attackers[2].size()==0)||(dis(attackers[2],king)>dis(queens[i],king)))\n attackers[2]=queens[i];\n }\n if(king[0]-queens[i][0]==-(king[1]-queens[i][1])&&king[0]<queens[i][0]){\n if((attackers[5].size()==0)||(dis(attackers[5],king)>dis(queens[i],king)))attackers[5]=queens[i];\n }\n }\n for(int i=0;i<8;i++)if(attackers[i].size())sol.push_back(attackers[i]);\n return sol;\n }\n};\n``` | 4 | 1 | ['C'] | 0 |
queens-that-can-attack-the-king | 100% faster | Moving each direction separately | Python | 100-faster-moving-each-direction-separat-kitc | \n\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n ans = []\n for i in range(king[0] - 1, -1, -1):\n if [i | krush_r_sonwane | NORMAL | 2022-11-30T16:21:16.101361+00:00 | 2022-11-30T16:27:07.520559+00:00 | 651 | false | \n```\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n ans = []\n for i in range(king[0] - 1, -1, -1):\n if [i, king[1]] in queens:\n ans.append([i, king[1]])\n break\n c1, c2 = king[0] - 1, king[1] - 1\n while c1 >= 0 and c2 >= 0:\n if [c1, c2] in queens:\n ans.append([c1, c2])\n break\n c1 -= 1\n c2 -= 1\n for i in range(king[1] - 1, -1, -1):\n if [king[0], i] in queens:\n ans.append([king[0], i])\n break\n for i in range(king[1] + 1, 8):\n if [king[0], i] in queens:\n ans.append([king[0], i])\n break\n c1, c2 = king[0] - 1, king[1] + 1\n while -1 < c1 and 8 > c2:\n if [c1, c2] in queens:\n ans.append([c1, c2])\n break\n c1, c2 = c1 - 1, c2 + 1\n c1, c2 = king[0] + 1, king[1] - 1\n while 8 > c1 and -1 < c2:\n if [c1, c2] in queens:\n ans.append([c1, c2])\n break\n c1 += 1\n c2 -= 1\n for i in range(king[0], 8):\n if [i, king[1]] in queens:\n ans.append([i, king[1]])\n break\n c1, c2 = king[0] + 1, king[1] + 1\n while 8 > c1 and 8 > c2:\n if [c1, c2] in queens:\n ans.append([c1, c2])\n break\n c1, c2 = c1 + 1, c2 + 1\n return ans\n```\n | 3 | 1 | ['Python', 'Python3'] | 0 |
queens-that-can-attack-the-king | [Java] O(n) solution with HashMap | java-on-solution-with-hashmap-by-olsh-wx2e | \nclass Solution {\n String horisontalLess = "horisontalLess";\n String horisontalBigger = "horisontalBigger";\n \n String verticalLess = "verticalL | olsh | NORMAL | 2022-07-30T22:01:00.466495+00:00 | 2022-07-30T22:01:00.466530+00:00 | 219 | false | ```\nclass Solution {\n String horisontalLess = "horisontalLess";\n String horisontalBigger = "horisontalBigger";\n \n String verticalLess = "verticalLess";\n String verticalBigger = "verticalBigger";\n \n String diahonal1Less = "diahonal1Less";\n String diahonal1Bigger = "diahonal1Bigger";\n \n String diahonal2Less = "diahonal2Less";\n String diahonal2Bigger = "diahonal2Bigger";\n \n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n Map<String,List<Integer>>candidates = new HashMap<>();\n String keyToInsert = null;\n for (int queen[]:queens){\n keyToInsert=null;\n if (queen[0]==king[0]){\n if (queen[1]>king[1] && (candidates.get(verticalBigger)==null || candidates.get(verticalBigger).get(1)>queen[1])) \n keyToInsert = verticalBigger;\n if (queen[1]<king[1] && (candidates.get(verticalLess)==null || candidates.get(verticalLess).get(1)<queen[1]))\n keyToInsert = verticalLess;\n }\n \n if (queen[1]==king[1]){\n if (queen[0]>king[0] && (candidates.get(horisontalBigger)==null || candidates.get(horisontalBigger).get(0)>queen[0])) \n keyToInsert = horisontalBigger;\n if (queen[0]<king[0] && (candidates.get(horisontalLess)==null || candidates.get(horisontalLess).get(0)<queen[0]))\n keyToInsert = horisontalLess;\n }\n \n \n if (queen[1]-queen[0]==king[1]-king[0]){\n if (queen[0]>king[0] && (candidates.get(diahonal1Bigger)==null || candidates.get(diahonal1Bigger).get(0)>queen[0])) \n keyToInsert = diahonal1Bigger;\n if (queen[0]<king[0] && (candidates.get(diahonal1Less)==null || candidates.get(diahonal1Less).get(0)<queen[0]))\n keyToInsert = diahonal1Less;\n }\n \n if (queen[1]+queen[0]==king[1]+king[0]){\n if (queen[0]>king[0] && (candidates.get(diahonal2Bigger)==null || candidates.get(diahonal2Bigger).get(0)>queen[0])) \n keyToInsert = diahonal2Bigger;\n if (queen[0]<king[0] && (candidates.get(diahonal2Less)==null || candidates.get(diahonal2Less).get(0)<queen[0]))\n keyToInsert = diahonal2Less;\n }\n \n if (keyToInsert!=null) {\n List<Integer>candidate = new ArrayList<>();\n candidate.add(queen[0]); \n candidate.add(queen[1]);\n candidates.put(keyToInsert, candidate);\n }\n }\n \n return new ArrayList<>(candidates.values());\n }\n}\n``` | 3 | 0 | [] | 0 |
queens-that-can-attack-the-king | C++ | checking for first queen in all 8 directions | faster than 100% | c-checking-for-first-queen-in-all-8-dire-rlhn | Checking for first queen in all 8 directions from the king\n\n\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& quee | ishika1727 | NORMAL | 2021-02-10T18:26:16.424140+00:00 | 2021-02-10T18:28:39.406223+00:00 | 454 | false | [](http://)Checking for first queen in all 8 directions from the king\n\n```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n int i,j;\n j=king[1]-1;\n i=king[0];\n vector<vector<int>> res;\n //row left\n while(j>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n j--;\n }\n //row right\n j=king[1]+1;\n while(j<8)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n j++;\n }\n // col up\n i=king[0]-1;\n j=king[1];\n while(i>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n i--;\n }\n //col down\n i=king[0]+1;\n while(i<8)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n i++;\n }\n // northwest\n i=king[0]-1;\n j=king[1]-1;\n while(i>=0 && j>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n i--;\n j--;\n }\n // northeast\n i=king[0]-1;\n j=king[1]+1;\n while(i>=0 && j<8)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n i--;\n j++;\n } \n // southwest\n i=king[0]+1;\n j=king[1]-1;\n while(i<8 && j>=0)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n i++;\n j--;\n }\n //southeast\n i=king[0]+1;\n j=king[1]+1;\n while(i<8 && j<8)\n {\n if(count(queens.begin(),queens.end(),vector<int> {i,j})==1)\n {\n res.push_back(vector<int>{i,j});\n break;\n }\n i++;\n j++;\n }\n return res;\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
queens-that-can-attack-the-king | Java Hash Set | java-hash-set-by-hobiter-fofg | \n public List<List<Integer>> queensAttacktheKing(int[][] qs, int[] kg) {\n List<List<Integer>> res = new ArrayList<>();\n Set<Integer> set = n | hobiter | NORMAL | 2020-07-16T18:34:20.639160+00:00 | 2020-07-16T18:34:20.639209+00:00 | 195 | false | ```\n public List<List<Integer>> queensAttacktheKing(int[][] qs, int[] kg) {\n List<List<Integer>> res = new ArrayList<>();\n Set<Integer> set = new HashSet<>();\n for (int[] q : qs) set.add(q[0] * 16 + q[1]);\n for (int i = -1; i < 2; i++) {\n for (int j = -1; j < 2; j++) {\n for (int k = 1; k < 8; k++) {\n int r = kg[0] + i * k, c = kg[1] + j * k;\n if (set.contains(r * 16 + c)) {\n res.add(List.of(r, c));\n break;\n }\n }\n }\n }\n return res;\n }\n``` | 3 | 1 | [] | 0 |
queens-that-can-attack-the-king | Simple Python 100% speed and 100% memory | simple-python-100-speed-and-100-memory-b-klhl | \n\n\n\ndef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n result = []\n seen = [[False for _ in range( | palaivishal | NORMAL | 2020-05-27T07:52:09.525798+00:00 | 2020-05-27T07:53:54.599843+00:00 | 411 | false | \n\n\n```\ndef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n result = []\n seen = [[False for _ in range(8)] for _ in range(8)] # create a 8 X 8 board \n \n for queen in queens: \n seen[queen[0]][queen[1]] = True # set true for the queens in the board with x and y co-ords\n \n directions = [-1, 0, 1] # 1 goes forward, -1 backwards and 0 not goes anywhere\n \n for dx in directions:\n for dy in directions: # these 2 loops help traverse all 9 sides around the king\n if dx == 0 and dy == 0:\n continue\n x = king[0]\n y = king[1]\n \n while x + dx >= 0 and x + dx < 8 and y + dy >= 0 and y + dy < 8:\n x = x + dx \n y = y + dy \n if seen[x][y]:\n result.append([x,y])\n break # this break is important and handles the case of a queen behind another queen \n return result\n``` | 3 | 0 | ['Dynamic Programming', 'Python', 'Python3'] | 1 |
queens-that-can-attack-the-king | Python 3 Easy to Understand.. O(n)t ime and Space (100% memory 93%time) | python-3-easy-to-understand-ont-ime-and-4dk63 | \tclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\\n \n #Converting the array int | werfree | NORMAL | 2020-05-23T15:19:57.195256+00:00 | 2020-05-23T15:21:59.653413+00:00 | 250 | false | \tclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\\\n \n #Converting the array into set for O(1) ---> Search\n Queens = set()\n \n for i,j in queens:\n Queens.add((i,j))\n \n \n #To store the result\n ans=[]\n \n \n \n \n #Recursive code\n def check(x,y,xPosition,yPosition):\n \n #Base Case\n \n if x>=8 or y>=8 or x<0 or y<0:\n return\n \n #Check whether the co-ordinate is present in the set or not\n if (x,y) in Queens:\n #If present add to ans and return\n ans.append([x,y])\n return\n #if not present go to the next coordinate \n # (xPosition and yPosition has value 0 1 -1 to decide the 8 direction )\n return check(x+xPosition,y+yPosition,xPosition,yPosition)\n \n \n #x and y co-ordinate of king\n xKing,yKing = king\n \n \n #All Eight Direction\n \n check(xKing,yKing,0,1) \n check(xKing,yKing,0,-1) \n check(xKing,yKing,1,0) \n check(xKing,yKing,-1,0) \n check(xKing,yKing,1,1) \n check(xKing,yKing,-1,-1) \n check(xKing,yKing,-1,1) \n check(xKing,yKing,1,-1) \n \n \n # return ans\n return ans\n\t\t\n\t\t# Please Upvote if you understand the code..\n\t\t\n\t\t\'\'\'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t _____ ___ __ ________ __ __\n\t / ___// | __ ______ _____ / /_____ _____ / ____/ / / /___ _____/ /_\n\t \\__ \\/ /| |/ / / / __ `/ __ \\/ __/ __ `/ __ \\ / / __/ /_/ / __ \\/ ___/ __ \\\n\t ___/ / ___ / /_/ / /_/ / / / / /_/ /_/ / / / / / /_/ / __ / /_/ (__ ) / / /\n\t/____/_/ |_\\__, /\\__,_/_/ /_/\\__/\\__,_/_/ /_/ \\____/_/ /_/\\____/____/_/ /_/\n\t\t\t /____/\n\n **************************************************\n _ _ ____ ____ ____ ____ ____ ____\n / )( \\( __)( _ \\( __)( _ \\( __)( __)\n \\ /\\ / ) _) ) / ) _) ) / ) _) ) _)\n (_/\\_)(____)(__\\_)(__) (__\\_)(____)(____)\n\n ***************************************************\n\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\'\'\'\n\n \n \n | 3 | 0 | ['Recursion', 'Python3'] | 1 |
queens-that-can-attack-the-king | C++ Solution (Using DFS) : Easy To Understand | c-solution-using-dfs-easy-to-understand-j01y4 | class Solution {\npublic:\n\n // Possible directions \n vector> dirs = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}} ;\n \n bool dfs(vecto | kaustav6422 | NORMAL | 2020-04-05T19:24:14.144571+00:00 | 2020-04-05T19:24:14.145099+00:00 | 302 | false | class Solution {\npublic:\n\n // Possible directions \n vector<vector<int>> dirs = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}} ;\n \n bool dfs(vector<int> queen, vector<int>& d, vector<int>& king, set<vector<int>>& s)\n {\n if (queen[0]<0||queen[1]<0||queen[0]>=8||queen[1]>=8)\n return false ;\n if (queen == king)\n return true ;\n \n if (!s.count({queen[0]+d[0],queen[1]+d[1]}))\n {\n if (dfs({queen[0]+d[0],queen[1]+d[1]}, d, king, s))\n return true ;\n }\n \n return false ;\n }\n // DFS\n // for each possible direction, check if you can kill the king. \n // If a black queen blocks your path, you can\'t\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n vector<vector<int>> res ;\n set<vector<int>> s(queens.begin(), queens.end()) ;\n \n for (auto x: queens)\n {\n for (auto d : dirs)\n {\n if (dfs(x,d,king,s))\n {\n res.push_back(x) ;\n break ;\n }\n }\n }\n return res ;\n \n }\n}; | 3 | 0 | [] | 0 |
queens-that-can-attack-the-king | Java Easy to Understand Solution | java-easy-to-understand-solution-by-nikc-g67w | \nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList();\n | nikcode | NORMAL | 2020-01-22T16:26:00.129826+00:00 | 2020-01-22T16:26:00.129879+00:00 | 191 | false | ```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList();\n int move[][] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};\n \n for(int i=0; i<8; i++) {\n int x = king[0] + move[i][0];\n int y = king[1] + move[i][1];\n while(isValid(x, y)) {\n if(queenExist(x, y, queens)) {\n result.add(Arrays.asList(x, y));\n break;\n }\n x += move[i][0];\n y += move[i][1];\n }\n }\n \n return result;\n }\n \n private boolean queenExist(int x, int y, int[][] queens) {\n for(int i=0; i<queens.length; i++) {\n if(queens[i][0] == x && queens[i][1] == y)\n return true;\n }\n return false;\n }\n \n private boolean isValid(int x, int y) {\n return (x >= 0 && x < 8 && y >= 0 & y < 8) ? true : false;\n }\n}\n``` | 3 | 0 | [] | 0 |
queens-that-can-attack-the-king | C++ O(n) 4ms O(1) memory, pretty solution with C++20 spaceship operator | c-on-4ms-o1-memory-pretty-solution-with-l2uh1 | While leetcode doesn\'t have the spaceship operator yet, I created a quick utility function that will mimic it. The way this solution works is by assigning each | ianshowell | NORMAL | 2019-12-16T18:09:29.950497+00:00 | 2019-12-16T18:11:59.519062+00:00 | 775 | false | While leetcode doesn\'t have the spaceship operator yet, I created a quick utility function that will mimic it. The way this solution works is by assigning each direction to an index number in constant time and then tracking the closest distance for each of the directions.\n\n```\nclass Solution {\npublic:\n int spaceship(int x, int y) {\n if (x > y)\n return 1;\n if (x < y)\n return -1;\n return 0;\n }\n \n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<int> direction_distances(9, -1);\n vector<vector<int>> queen_coords(9);\n \n for (auto queen : queens) {\n int dx = queen[0] - king[0];\n int dy = queen[1] - king[1];\n if (dx == 0 or dy == 0 or abs(dx) == abs(dy)) {\n // Queen is able to attack. Now to check if closest\n // int direction = (dy <=> 0) * 3 + (dx <=> 0) + 4;\n int direction = spaceship(dy, 0) * 3 + spaceship(dx, 0) + 4;\n int distance = dy == 0 ? abs(dx) : abs(dy);\n if (direction_distances[direction] == -1 or direction_distances[direction] > distance) {\n direction_distances[direction] = distance;\n queen_coords[direction] = queen;\n }\n }\n }\n \n vector<vector<int>> result;\n for (size_t i = 0; i < 9; i++) {\n if (direction_distances[i] != -1)\n result.push_back(queen_coords[i]);\n }\n return result;\n }\n};\n``` | 3 | 0 | ['C'] | 2 |
queens-that-can-attack-the-king | Python simple: 99% speed, 100% memory | python-simple-99-speed-100-memory-by-jwu-impx | \nout = []\ndirections = [[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,-1],[1,-1],[-1,1]]\nfor d in directions:\n\ti,j = king[0],king[1]\n\twhile 0<=i<=8 and 0<=j<=8:\n\ | jwu0407 | NORMAL | 2019-12-01T20:57:08.025316+00:00 | 2019-12-01T20:59:25.243105+00:00 | 277 | false | ```\nout = []\ndirections = [[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,-1],[1,-1],[-1,1]]\nfor d in directions:\n\ti,j = king[0],king[1]\n\twhile 0<=i<=8 and 0<=j<=8:\n\t\ti += d[0]\n\t\tj += d[1]\n\t\tif [i,j] in queens:\n\t\t\tout.append([i,j])\n\t\t\tbreak\nreturn out\n```\n | 3 | 0 | ['Python'] | 0 |
queens-that-can-attack-the-king | Easy to understand | easy-to-understand-by-andyoung-aojy | ``\nvar queensAttacktheKing = function(queens, king) {\n const map = {};\n queens.forEach(q => map[q.join(\',\')] = 1);\n \n // for eight directions, find t | andyoung | NORMAL | 2019-11-10T19:34:51.978350+00:00 | 2019-11-10T19:43:02.853096+00:00 | 338 | false | ```\nvar queensAttacktheKing = function(queens, king) {\n const map = {};\n queens.forEach(q => map[q.join(\',\')] = 1);\n \n // for eight directions, find the first queen\n const ans = [];\n const dirs = [[1, 0], [0, 1], [-1, 0], [0, -1], [-1, 1], [1, -1], [1, 1], [-1, -1]];\n // record if needed to go further for each direction\n const visited = new Array(8).fill(false);\n let step = 1;\n while (step < 8) {\n dirs.forEach((d, i) => {\n if (!visited[i]) {\n let x = king[0] + step * d[0];\n let y = king[1] + step * d[1];\n if (x < 0 || y < 0 || x > 7 || y > 7) {\n visited[i] = true;\n } else if (map[`${x},${y}`]) {\n visited[i] = true;\n ans.push([x, y]);\n }\n }\n });\n step += 1;\n }\n \n return ans;\n}; | 3 | 1 | ['JavaScript'] | 0 |
queens-that-can-attack-the-king | Python 3 in 1 line | python-3-in-1-line-by-l1ne-z9k9 | \n# 12 clear lines\npython\nDIRS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]\n\nclass Solution:\n def queensAttacktheKing(self, queens, | l1ne | NORMAL | 2019-10-18T05:51:59.169236+00:00 | 2019-10-18T05:53:28.040769+00:00 | 361 | false | \n# 12 clear lines\n```python\nDIRS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]\n\nclass Solution:\n def queensAttacktheKing(self, queens, king):\n q = {(r,c) for r,c in queens}\n r, c = king\n result = []\n for dr, dc in DIRS:\n for i in range(8):\n r2, c2 = r+dr*i, c+dc*i\n if not (0 <= r2 < 8 and 0 <= c2 < 8): break\n if (r2, c2) in q:\n result.append([r2, c2])\n break\n return result\n```\n\n# 4 reasonable lines\n```python\nDIRS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if i or j]\n\nclass Solution:\n def queensAttacktheKing(self, queens, king):\n q = {(r,c) for r,c in queens}\n r, c = king\n return list(filter(None, (next(([r+dr*i, c+dc*i] for i in range(8) if (r+dr*i, c+dc*i) in q), None) for dr, dc in DIRS)))\n```\n\n# 2 compact lines\n```python\nclass Solution:\n def queensAttacktheKing(self, queens, king, DIRS=[(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)]):\n q = {(r,c) for r,c in queens}\n return list(filter(None, (next(([king[0]+dr*i, king[1]+dc*i] for i in range(8) if (king[0]+dr*i, king[1]+dc*i) in q), None) for dr, dc in DIRS)))\n```\n\n# 1 disgusting line\n```python\nclass Solution:\n def queensAttacktheKing(self, queens, king, DIRS=[(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)], q=[0]):\n return q.__setitem__(0, {(r,c) for r,c in queens}) or list(filter(None, (next(([king[0]+dr*i, king[1]+dc*i] for i in range(8) if (king[0]+dr*i, king[1]+dc*i) in q[0]), None) for dr, dc in DIRS)))\n``` | 3 | 0 | [] | 1 |
queens-that-can-attack-the-king | [Python3] O(n) Solution with Explanation | python3-on-solution-with-explanation-by-cgmu2 | Optimized Solution Explanation\nThe idea is to search all possible paths starting at the king location. There can be at most 8 queens in the return array becaus | laser | NORMAL | 2019-10-13T04:08:09.633227+00:00 | 2019-10-13T18:15:31.381813+00:00 | 462 | false | **Optimized Solution Explanation**\nThe idea is to search all possible paths starting at the king location. There can be at most 8 queens in the return array because the queen can only move in 8 directions.\nSteps:\n1. Create a queens set so you can do on O(1) operation check to see if the queen is in the path.\n2. Starting from the king location, check all 8 directions to find the first queen in that path.\n3. Exit early if you\'ve found 8 queens.\n\n**Time Complexity**\nO(n) (n=number of queens) to store the queens into a set\nAll other operations are constant as the board is fixed at 8 rows x 8 cols\nRuntime: 48 ms, faster than 100.00% of Python3 online submissions\n\n**Space Complexity**\nO(n) (n=number of queens) to store the queens into a set\nMemory Usage: 13.8 MB, less than 100.00% of Python3 online submissions\n\n**Code**\n```\nBOARD_ROWS = 8\nBOARD_COLS = 8\nclass Solution:\n def queensAttacktheKing(self, queens: "List[List[int]]", king: "List[int]") -> "List[List[int]]":\n def check(r,c,ro,co):\n while (r >= 0 and r < BOARD_ROWS and\n c >= 0 and c < BOARD_COLS):\n if (r,c) in queens:\n return (r,c)\n r += ro\n c += co\n return None\n\n # 1. Create a queens set so you can do on O(1) operation check\n\t\t# to see if the queen is in the path.\n queens = set([(r,c) for r,c in queens]) # O(q) time, and space\n\n res = []\n\t\t# 2. Starting from the king location, check all 8 directions to find the\n\t\t# first queen in that path.\n for ro,co in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]: # O(8) time\n check_res = check(king[0],king[1],ro,co) # O(8) time\n if check_res != None:\n res.append([check_res[0],check_res[1]])\n\t\t\t\t# 3. Exit early if you\'ve found 8 queens.\n if len(check_res) == 8:\n return res\n\n return res\n```\n\n**Unoptimized O(nlogn) Solution Explanation**\nThe idea is to:\n1. Build a board to determine if a queen can reach the king\n2. Sort the queens based on closest proximity to the king. This is important because it will mark queen locations that block other further out queens.\n3. Use this sorted queens list as a stack to use DFS.\n4. Check all movement directions for all queens, and if it is able to get to the king, then mark it on the board, and add it to the results.\n\n**Time Complexity**\nO(qlogq + 2q) (q=number of queens) -> O(nlogn)\n\n**Space Complexity**\nO(1) because the board always has a constant/static limit of 8 rows and 8 columns\n\n**Code**\n```\nclass Solution:\n def queensAttacktheKing(self, queens: "List[List[int]]", king: "List[int]") -> "List[List[int]]":\n def check(r,c,ro,co):\n while (r >= 0 and r < len(b) and\n c >= 0 and c < len(b[0]) and\n b[r][c] != 0):\n if b[r][c] == 0:\n return False\n if r == king[0] and c == king[1]:\n return True\n r += ro\n c += co\n return False\n\n def generate_board(mr,mc):\n for r in range(mr+1):\n b.append([])\n for c in range(mc+1):\n b[r].append(1)\n\n mr = mc = 0\n for qr,qc in queens: # O(q) time\n mr = max(mr, qr)\n mc = max(mc, qc)\n mr = max(mr, king[0])\n mc = max(mc, king[1])\n\n b = [] # O(1) space bc board has constant size of 8x8\n generate_board(mr,mc) # O(1) time bc board has constant size of 8x8\n\n queens.sort(key=lambda q: abs(q[0] - king[0]) + abs(q[1] - king[1]), reverse=True) # O(qlogq) time\n\n res = []\n while queens: # O(q) time\n qr, qc = queens.pop()\n\n for ro,co in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:\n if check(qr,qc,ro,co) == True: # O(1) time bc the board has a constant size of 8x8\n b[qr][qc] = 0\n res.append([qr,qc])\n break\n\n return res\n``` | 3 | 0 | [] | 1 |
queens-that-can-attack-the-king | Efficient and Simple Solution for Queens That Can Attack the King | efficient-and-simple-solution-for-queens-u2d1 | IntuitionThe problem requires us to find all queens that can attack the king in an 8×8 chessboard. A queen can move horizontally, vertically, and diagonally, me | princesharma21102004 | NORMAL | 2025-02-06T13:12:57.387071+00:00 | 2025-02-06T13:12:57.387071+00:00 | 68 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to find all queens that can attack the king in an 8×8 chessboard. A queen can move horizontally, vertically, and diagonally, meaning we need to check in 8 possible directions to see if there is a queen in the path of the king.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Store Queen Positions Efficiently:
- We use a set<vector<int>> to store the queens' positions, allowing for O(1) average-time lookup when checking if a queen exists at a given position.
2. Traverse in 8 Directions:
- We define 8 possible movement directions (left, right, up, down, and four diagonal directions).
- We iterate outward from the king's position in each direction.
- If we find a queen in that direction (i.e., the position exists in the set), we add it to the result and stop checking further in that direction.
3. Return the List of Attacking Queens:
- The final list contains all the queens that can attack the king.
# Complexity
- Time complexity: O(1)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
Inserting queens into the set: O(q), where q is the number of queens (at most 64).
Checking 8 directions:
In the worst case, the loop runs up to 8 times per direction (since an 8×8 board has at most 8 cells in any direction).
Since we have 8 directions, the worst-case scenario is O(8 × 8) = O(64) = O(1).
Overall time complexity: O(1) (constant time) because the board size is fixed at 8×8.
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
Set to store queens: O(q) in the worst case (at most 64 queens).
Result vector: O(8) (maximum 8 attacking queens).
Overall space complexity: O(1) (since the board size is fixed, space usage does not grow dynamically).

# Code
```cpp []
/*
AUTHOR - Prince Sharma
DATE - 6/2/2025 18:37
PROBLEM - Queens That Can Attack the King
NOTATION - O -> worst case complexcity, S -> for space complexity, T -> for time complexity
COMPLEXITY - TO(1), SO(1)
*/
class Solution
{
public:
vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king)
{
set<vector<int>> queens_search;
vector<vector<int>> queens_attacking;
vector<pair<int, int>> directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}, // Horizontal & Vertical
{-1, -1}, {1, -1}, {-1, 1}, {1, 1}}; // Diagonal
for(auto queen:queens) queens_search.insert(queen);
for(auto [rinc, linc]:directions)
for(int row=king[0],column=king[1];row>=0 && row<8 && column>=0 && column<8; row+=rinc, column+=linc)
if(queens_search.count({row, column}))
{queens_attacking.push_back({row, column}); break;}
return queens_attacking;
}
};
```
 | 2 | 0 | ['Array', 'Matrix', 'Simulation', 'C++'] | 0 |
queens-that-can-attack-the-king | [Java] Easy solution | java-easy-solution-by-ytchouar-5yoh | java\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(final int[][] queens, final int[] king) {\n final boolean[][] grid = new boole | YTchouar | NORMAL | 2024-06-16T04:28:39.463039+00:00 | 2024-06-16T04:28:39.463072+00:00 | 125 | false | ```java\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(final int[][] queens, final int[] king) {\n final boolean[][] grid = new boolean[8][8];\n\n for(final int[] queen : queens)\n grid[queen[0]][queen[1]] = true;\n\n final int[][] directions = new int[][] { { 0, 1 }, { 1, 0 }, { 1, 1 }, { 0, -1 }, { -1, 0 }, { -1, -1 }, { -1, 1 }, { 1, -1 } };\n final List<List<Integer>> result = new ArrayList();\n\n for(final int[] direction : directions) {\n int i = king[0], j = king[1];\n\n while(i < 8 && j < 8 && i >= 0 && j >= 0) {\n if(grid[i][j]) {\n result.add(List.of(i, j));\n break;\n }\n\n i += direction[0];\n j += direction[1];\n }\n }\n\n return result;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
queens-that-can-attack-the-king | Easy checking queen can attack or not with row col and diagonal check | easy-checking-queen-can-attack-or-not-wi-h9qw | Intuition\n Describe your first thoughts on how to solve this problem. \nFirstly understand the problem the queen can attack the king if thereb is no queen obst | bura_uday | NORMAL | 2024-03-09T14:49:05.630556+00:00 | 2024-03-09T14:49:05.630575+00:00 | 19 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirstly understand the problem the queen can attack the king if thereb is no queen obstacle and the king is row or col or diagonal to king so the king can attack\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake a matrix of 8*8 and fill -1 at all indices then fill 1 in king position then fill 0 with each queen then take nested loops to find the queen if queen is founded then check can it able to attack the king with no obstacles of queens\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n*2)\n\n- Space complexity:\n# <!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> al=new ArrayList<>();\n\n int nums[][]=new int[8][8];\n for(int i=0;i<8;i++)\n {\n for(int j=0;j<8;j++)\n {\n nums[i][j]=-1;\n }\n }\n nums[king[0]][king[1]]=1;\n int c=0;\n for(int i=0;i<queens.length;i++)\n {\n nums[queens[i][0]][queens[i][1]]=0;\n }\n for(int i=0;i<nums.length;i++)\n {\n \n for(int j=0;j<nums.length;j++)\n {\n if(nums[i][j]==0)\n if(check(nums,i,j)==1)\n {\n ArrayList<Integer> t=new ArrayList<Integer>();\n c++;\n t.add(i);\n t.add(j);\n al.add(t);\n }\n }\n \n }\n return al;\n \n }\n public int check(int nums[][],int r,int c)\n {\n int x=0;\n for(int i=c+1;i<nums.length;i++)\n {\n if(nums[r][i]==1)\n {\n return 1;\n }\n if(nums[r][i]==0)\n {\n break;\n }\n }\n for(int i=c-1;i>=0;i--)\n {\n if(nums[r][i]==1)\n {\n return 1;\n }\n if(nums[r][i]==0)\n {\n break;\n }\n }\n for(int i=r+1;i<nums.length;i++)\n {\n if(nums[i][c]==1)\n {\n return 1;\n }\n if(nums[i][c]==0)\n {\n break;\n }\n }\n for(int i=r-1;i>=0;i--)\n {\n if(nums[i][c]==1)\n {\n return 1;\n }\n if(nums[i][c]==0)\n {\n break;\n }\n }\n for(int i=r-1,j=c-1;i>=0&&j>=0;i--,j--)\n {\n if(nums[i][j]==1)\n {\n return 1;\n }\n if(nums[i][j]==0)\n {\n break;\n }\n }\n for(int i=r+1,j=c+1;i<nums.length&&j<nums.length;i++,j++)\n {\n if(nums[i][j]==1)\n {\n return 1;\n }\n if(nums[i][j]==0)\n {\n break;\n }\n }\n for(int i=r+1,j=c-1;i<nums.length&&j>=0;i++,j--)\n {\n if(nums[i][j]==1)\n {\n return 1;\n }\n if(nums[i][j]==0)\n {\n break;\n }\n }\n for(int i=r-1,j=c+1;i>=0&&j<nums.length;i--,j++)\n {\n if(nums[i][j]==1)\n {\n return 1;\n }\n if(nums[i][j]==0)\n {\n break;\n }\n }\n return 0;\n }\n}\n``` | 2 | 0 | ['Array', 'Java'] | 0 |
queens-that-can-attack-the-king | Beats 100% | ✅ | beats-100-by-shadab_ahmad_khan-nxre | \n_____\n\n# Up Vote if Helps\n\n_____\n\n\n# Code\n\nclass Solution {\n List<List<Integer>> ans=new ArrayList<>();\n int[][] board;\n public List<List | Shadab_Ahmad_Khan | NORMAL | 2024-02-21T11:05:09.818966+00:00 | 2024-02-21T11:05:09.819011+00:00 | 280 | false | \n______________________________________\n\n# **Up Vote if Helps**\n\n______________________________________\n\n\n# Code\n```\nclass Solution {\n List<List<Integer>> ans=new ArrayList<>();\n int[][] board;\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n board=new int[8][8];\n for(int i=0; i<queens.length; i++){\n int row=queens[i][0];\n int col=queens[i][1];\n board[row][col]=1;\n }\n top(king[0],king[1]);\n bottom(king[0],king[1]);\n left(king[0],king[1]);\n right(king[0],king[1]);\n topleft(king[0],king[1]);\n topRight(king[0],king[1]);\n bottomLeft(king[0],king[1]);\n bootomRight(king[0],king[1]);\n return ans;\n }\n public void top(int row, int col){\n for(int i=row ; i>=0 ; i--){\n if(board[i][col]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(i);\n temp.add(col);\n ans.add(temp);\n return;\n }\n }\n }\n public void bottom(int row, int col){\n for(int i=row; i<8; i++){\n if(board[i][col]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(i);\n temp.add(col);\n ans.add(temp);\n return;\n } \n }\n }\n public void left(int row, int col){\n for(int j=col; j>=0; j--){\n if(board[row][j]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(row);\n temp.add(j);\n ans.add(temp);\n return;\n } \n }\n }\n public void right(int row, int col){\n for(int j=col ; j<8 ; j++){\n if(board[row][j]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(row);\n temp.add(j);\n ans.add(temp);\n return;\n }\n }\n }\n public void topleft(int row, int col){\n for(int i=row, j=col; i>=0 && j>=0 ; i--,j--){\n if(board[i][j]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(i);\n temp.add(j);\n ans.add(temp);\n return;\n } \n }\n }\n public void topRight(int row, int col){\n for(int i=row, j=col; i>=0 && j<8 ; i--,j++){ \n if(board[i][j]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(i);\n temp.add(j);\n ans.add(temp);\n return;\n } \n }\n }\n public void bottomLeft(int row, int col){\n for(int i=row,j=col; i<8 && j>=0 ; i++, j--){\n if(board[i][j]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(i);\n temp.add(j);\n ans.add(temp);\n return;\n } \n }\n }\n public void bootomRight(int row, int col){\n for(int i=row, j=col; i<8 && j<8 ; i++,j++){\n if(board[i][j]==1){\n List<Integer> temp=new ArrayList<>();\n temp.add(i);\n temp.add(j);\n ans.add(temp);\n return;\n }\n }\n } \n}\n```\n______________________________________\n\n# **Up Vote if Helps**\n\n______________________________________ | 2 | 0 | ['Java'] | 0 |
queens-that-can-attack-the-king | Clean & concise solution , no need different loops !! | clean-concise-solution-no-need-different-fjnl | Intuition\nInstead of checking from all queens , we can check from the king.\n\nHere i + dir[d] gives us next i and j + (dir[d + 1]) gives us the next j in the | kushalnagwanshicloud | NORMAL | 2023-04-16T09:53:59.463377+00:00 | 2023-04-16T09:53:59.463424+00:00 | 337 | false | # Intuition\n**Instead of checking from all queens , we can check from the king.**\n\nHere `i + dir[d]` gives us **next** `i` and `j + (dir[d + 1])` gives us the **next** `j` in the current direction.\n\nexample , `{dir[0] , dir[1]}` gives us the **update** `{1 , 0}` which is the required update for **down** direction.\n\n`{dir[1] , dir[2]}` gives us `{ 0 , -1 }` for **up** direction.\n\n`{dir[7] , dir[8]}` gives us `{ 1 , 1 }` for **down-right** direction.\n\nwe can get all **8 directions** like this !!\n# Code\n```\nclass Solution {\npublic:\n bool isValid(int x , int y ){\n if( x < 0 or y < 0 or x >= 8 or y >= 8 ) return false ; \n return true ; \n }\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> Q(8 , vector<int>(8) ) ; // positions of queens ; \n vector<vector<int>> res ; \n\n for(auto &pos : queens ){\n Q[pos[0]][pos[1]] = true ; \n }\n\n int dir[9] = { 1 , 0 , -1 , 0 , 1 , -1 , -1 , 1, 1 } ; \n\n for(int d = 0 ; d < 8 ; d++){\n int i = king[0] , j = king[1] ;\n while( isValid(i , j )){\n if(Q[i][j]) {\n res.push_back( {i , j} ); \n break ; // no other queen can directly hit the king in this direction.\n }\n i += dir[d] ;\n j += dir[d+1] ;\n }\n }\n\n return res ; \n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
queens-that-can-attack-the-king | queens ♛ Attacks King ♚ | queens-attacks-king-by-saeed20359-eyy9 | Intuition\n- This code is a Java implementation of a solution to the Queens That Can Attack the King problem on LeetCode. The problem involves finding all the q | saeed20359 | NORMAL | 2023-02-23T18:34:29.388741+00:00 | 2023-02-23T18:34:29.388777+00:00 | 252 | false | # Intuition\n- This code is a Java implementation of a solution to the `Queens That Can Attack the King` problem on `LeetCode`. The problem involves finding all the queens on a chessboard that can attack a given king.\n\n# Complexity\n- **Time complexity:**\nThe time complexity of this code is `O(q)`, where `q` is the number of queens. The for loop that iterates over the queens takes `O(q)` time. The inline and NearMore methods both have constant time complexity, so the total time complexity of the algorithm is dominated by the for loop. The worst-case scenario is when all queens are in line with the king, which requires checking all `q` queens. Therefore, the overall time complexity is `O(q)`.\n\n- **Space complexity:**\nThe space complexity of this code is `O(1)` since it only uses a fixed amount of memory to store the indexes array, `dy`, `dx`, and index variables. The number of queens and the king\'s position are given as inputs, but they are not used to allocate memory dynamically. The lists variable used to store the result has a maximum length of `8`, which is the maximum number of queens that can attack the king.\n\n# Code\n- This line declares the `queensAttacktheKing` method, which takes two inputs: an array of queen positions `queens` and the position of the king `king`. The method returns a list of positions of queens that can attack the king.\n``` java\npublic List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king)\n```\n- This line initializes the indexes array to `-1` for all eight directions (up-left, up, up-right, right, down-right, down, down-left, left).\n``` java\nint[] indexes = new int[]{-1, -1, -1, -1, -1, -1, -1, -1};\n```\n- These lines declare three integer variables to be used in the loop.\n``` java\nint dy, dx, index;\n```\n- This line starts a loop that iterates over all the queens on the board.\n``` java\nfor (int i = 0; i < queens.length; i++)\n```\n- This line checks if the current queen is in the same row, column, or diagonal as the king. The `inline` method is called to check this.\n``` java\nif (inline(queens[i], king))\n```\n- These lines calculate the vertical and horizontal distances between the `queen` and the `king`.\n``` java\ndy = king[1] - queens[i][1];\ndx = king[0] - queens[i][0];\n```\n- These lines calculate the `index` of the `indexes` array for the direction of the `queen` relative to the `king`. If the `queen` is in the same row, the `index` will be `7` or `3`. If the `queen` is in the same column, the `index` will be `1` or `5`. If the `queen` is in a diagonal direction, the `index` will be `0`, `2`, `4`, or `6`.\n``` java\n/* \n up-left -> 0, \n up -> 1, \n up-right -> 2, \n right -> 3, \n down-right -> 4, \n down -> 5, \n down-left -> 6, \n left -> 7\n*/\nif (dx == 0) index = dy < 0 ? 1 : 5;\nelse if (dy == 0) index = dx < 0 ? 7 : 3;\nelse if (dy < 0) index = dx < 0 ? 0 : 2;\nelse index = dx < 0 ? 6 : 4;\n```\n- This line updates the `indexes` array if the current `queen` is closer to the `king` in the given direction than the previous `queen` (if any) in that direction. The `NearMore` method is called to check this.\n\n``` java\nif (indexes[index] == -1 || NearMore(queens[i], queens[indexes[index]], king)) indexes[index] = i;\n```\n- Finally, this block of code creates a list of `queen` positions from the `indexes` array and returns it.\n``` java\nList<List<Integer>> lists = new ArrayList<>();\nfor (int i : indexes) if (i != -1) lists.add(Arrays.asList(queens[i][0], queens[i][1]));\nreturn lists;\n```\n- The `inline` method checks whether two pairs of coordinates are in the same row, column, or diagonal, by checking whether their x-coordinates are equal, their y-coordinates are equal, or the absolute difference of their x-coordinates equals the absolute difference of their y-coordinates, respectively.\n``` java\npublic boolean inline(int[] pair1, int[] pair2) {\n return\n pair1[0] == pair2[0] || // case row eq\n pair1[1] == pair2[1] || // case col eq\n Math.abs(pair1[1] - pair2[1]) == Math.abs(pair1[0] - pair2[0]); // case cross\n}\n```\n- The `NearMore` method checks which of `two pairs` of coordinates is closer to a target pair of coordinates. If the `two pairs` have the same x-coordinate (i.e., they are in the same row), it returns true if the absolute difference of their y-coordinates to the target is less than the corresponding difference of the other pair. Similarly, if the two pairs have the same y-coordinate (i.e., they are in the same column), it returns true if the absolute difference of their x-coordinates to the target is less than the corresponding difference of the other pair. If neither of these conditions hold, it returns `true` if the distance of the first pair from the target is `less than` the distance of the second pair from the target.\n``` java\npublic boolean NearMore(int[] pair1, int[] pair2, int[] target) {\n // case raw\n if (pair1[0] == pair2[0]) return Math.abs(target[1] - pair1[1]) < Math.abs(target[1] - pair2[1]);\n // case column\n if (pair1[1] == pair2[1]) return Math.abs(target[0] - pair1[0]) < Math.abs(target[0] - pair2[0]);\n // case cross\n return // dy_1^2 + dx_1^2 < dy_2^2 + dx_2^2\n Math.pow(target[1] - pair1[1], 2) + Math.pow(target[0] - pair1[0], 2) <\n Math.pow(target[1] - pair2[1], 2) + Math.pow(target[0] - pair2[0], 2);\n}\n```\n# Full Code\n``` java\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n // {\n // up-left -> 0, \n // up -> 1, \n // up-right -> 2, \n // right -> 3, \n // down-right -> 4, \n // down -> 5, \n // down-left -> 6, \n // left -> 7\n // } \n int[] indexes = new int[]{-1, -1, -1, -1, -1, -1, -1, -1};\n int dy, dx, index;\n for (int i = 0; i < queens.length; i++) {\n if (inline(queens[i], king)) // in line with king\n {\n dy = king[1] - queens[i][1];\n dx = king[0] - queens[i][0];\n // in column\n if (dx == 0) index = dy < 0 ? 1 /* up */ : 5 /* down */;\n // in row\n else if (dy == 0) index = dx < 0 ? 7 /* left */ : 3 /* right */;\n // cross-up\n else if (dy < 0) index = dx < 0 ? 0 /* up-left */ : 2 /* up-right */;\n // cross-down\n else index = dx < 0 ? 6 /* down-left */ : 4 /* down-right */;\n if (indexes[index] == -1 || NearMore(queens[i], queens[indexes[index]], king)) indexes[index] = i;\n }\n }\n // setup result\n List<List<Integer>> lists = new ArrayList<>();\n for (int i : indexes) if (i != -1) lists.add(Arrays.asList(queens[i][0], queens[i][1]));\n return lists;\n }\n\n public boolean inline(int[] pair1, int[] pair2) {\n return\n pair1[0] == pair2[0] || // case row eq\n pair1[1] == pair2[1] || // case col eq\n Math.abs(pair1[1] - pair2[1]) == Math.abs(pair1[0] - pair2[0]); // case cross\n }\n\n public boolean NearMore(int[] pair1, int[] pair2, int[] target) {\n // case raw\n if (pair1[0] == pair2[0]) return Math.abs(target[1] - pair1[1]) < Math.abs(target[1] - pair2[1]);\n // case column\n if (pair1[1] == pair2[1]) return Math.abs(target[0] - pair1[0]) < Math.abs(target[0] - pair2[0]);\n // case cross\n return // dy_1^2 + dx_1^2 < dy_0^2 + dx_0^2\n Math.pow(target[1] - pair1[1], 2) + Math.pow(target[0] - pair1[0], 2) <\n Math.pow(target[1] - pair2[1], 2) + Math.pow(target[0] - pair2[0], 2);\n }\n}\n```\n\n\n | 2 | 0 | ['Array', 'Math', 'Java'] | 0 |
queens-that-can-attack-the-king | Easy Python Code | Long But Easy Approach ✔ | easy-python-code-long-but-easy-approach-7uf6y | Python3 Solution\n\n# Code\n\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n l = []\n | ashish_2298744 | NORMAL | 2023-01-26T08:41:37.735244+00:00 | 2024-10-06T06:52:16.539165+00:00 | 324 | false | Python3 Solution\n\n# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n l = []\n # to traverse in straight left of king\'s position\n for i in range(king[1], -1, -1):\n if [king[0], i] in queens:\n l.append([king[0], i])\n break\n # to traverse in straight right of king\'s position\n for i in range(king[1], 8, 1):\n if [king[0], i] in queens:\n l.append([king[0], i])\n break\n # to traverse staright above king\'s position\n for i in range(king[0], -1, -1):\n if [i, king[1]] in queens:\n l.append([i, king[1]])\n break\n # to traverse straight down king\'s position\n for i in range(king[0], 8, 1):\n if [i, king[1]] in queens:\n l.append([i, king[1]])\n break\n\n # to traverse diagonally right down from king\'s position\n for i in range(1, 8):\n if [king[0] + i, king[1] + i] in queens:\n l.append([king[0] + i, king[1] + i])\n break\n if king[0] + i > 7 or king[1] + i > 7:\n break\n # to traverse diagonally left up from king\'s position\n for i in range(1, 8):\n if [king[0] - i, king[1] - i] in queens:\n l.append([king[0] - i, king[1] - i])\n break\n if king[0] - i < 0 or king[1] - i < 0:\n break\n # to traverse diagonally right up from king\'s position\n for i in range(1, 8):\n if [king[0] - i, king[1] + i] in queens:\n l.append([king[0] - i, king[1] + i])\n break\n if king[0] - i < 0 or king[1] + i > 7:\n break\n # to traverse diagonally left down from king\'s position\n for i in range(1, 8):\n if [king[0] + i, king[1] - i] in queens:\n l.append([king[0] + i, king[1] - i])\n break\n if king[0] + i > 7 or king[1] - i < 0:\n break\n return l\n\n\n``` | 2 | 0 | ['Python3'] | 1 |
queens-that-can-attack-the-king | c++ | simple | easy to understand | c-simple-easy-to-understand-by-akshat061-jxhs | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& arr, vector<int>& king) {\n set<pair<int,int>>st;\n\t for(i | akshat0610 | NORMAL | 2022-10-05T08:24:30.294187+00:00 | 2022-10-05T08:24:30.294228+00:00 | 570 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& arr, vector<int>& king) {\n set<pair<int,int>>st;\n\t for(int i=0;i<arr.size();i++)\n\t {\n\t \tst.insert(make_pair(arr[i][0],arr[i][1]));\n\t }\n\t vector<vector<int>>ans;\n\t \n int row=king[0]; //row\n\t int col=king[1]; //col\n\t \n\t //checking the first part...1\n //row will be constant\n while(col<8)\n {\n \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t col++;\n\t }\n\t \n\t //checking the second part...2\n\t //row will be constant\n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(col>=0)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t col--;\n\t }\n\t \n\t //checking the third part...3\n\t //col will be constant\n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(row>=0)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t row--;\n\t }\n\t \n\t \n\t //checking the fourth part...4\n\t //col will be constant\n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(row<8)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t row++;\n\t }\n\t \n\t //checking the fifth part...5\n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(row>=0 and col<8)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t row--;\n\t col++;\n\t }\n\t \n\t //checking the sixth part...6\n\t \n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(row<8 and col>=0)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t row++;\n\t col--;\n\t }\n\t \n\t //checking the third part...7\n\n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(row>=0 and col>=0)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t row--;\n\t col--;\n\t }\n\t \n\t //checking the third part...8\n\t \n\t row=king[0]; //row\n\t col=king[1]; //col\n\t \n\t while(row<8 and col<8)\n\t {\n\t \tif(st.find(make_pair(row,col))!=st.end())\n \t{\n \t ans.push_back({row,col}); //we found a queen attacking the king \t\n \t break;\n\t }\n\t row++;\n\t col++;\n\t }\n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
queens-that-can-attack-the-king | c++ | simple | easy to understand | c-simple-easy-to-understand-by-venomhigh-nexa | ```\nclass Solution {\npublic:\n vector> queensAttacktheKing(vector>& queens, vector& king) {\n vector > ans;\n int row = king[0], col = king[1 | venomhighs7 | NORMAL | 2022-09-24T03:50:22.707349+00:00 | 2022-09-24T03:50:22.707411+00:00 | 243 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int> > ans;\n int row = king[0], col = king[1];\n vector<vector<bool> > queen(8, vector<bool>(8, false));\n \n for(auto &q: queens) \n queen[q[0]][q[1]] = true;\n \n //west side\n for(int j=col-1; j>=0; j--){\n if(queen[row][j]){\n ans.push_back({row, j});\n break;\n }\n }\n \n //east side\n for(int j=col+1; j<8; j++){\n if(queen[row][j]){\n ans.push_back({row, j});\n break;\n }\n }\n \n //north side\n for(int i=row-1; i>=0; i--){\n if(queen[i][col]){\n ans.push_back({i, col});\n break;\n }\n }\n \n //south side\n for(int i=row+1; i<8; i++){\n if(queen[i][col]){\n ans.push_back({i, col});\n break;\n }\n }\n \n //north west side\n for(int i=row-1, j=col-1; i>=0 && j>=0; i--, j--){\n if(queen[i][j]){\n ans.push_back({i, j});\n break;\n }\n }\n \n //south west side\n for(int i=row+1, j=col-1; i<8 && j>=0; i++, j--){\n if(queen[i][j]){\n ans.push_back({i, j});\n break;\n }\n }\n \n //south east side\n for(int i=row+1, j=col+1; i<8 && j<8; i++, j++){\n if(queen[i][j]){\n ans.push_back({i, j});\n break;\n }\n }\n \n //north east side\n for(int i=row-1, j=col+1; i>=0 && j<8; i--, j++){\n if(queen[i][j]){\n ans.push_back({i, j});\n break;\n }\n }\n \n return ans;\n }\n}; | 2 | 0 | [] | 0 |
queens-that-can-attack-the-king | Python (35 ms, 98.93 %, 13.9 Mb, 89.29 %) | python-35-ms-9893-139-mb-8929-by-takeich-nljs | python\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n # To attack the king, maximal | TakeIchiru | NORMAL | 2022-08-02T09:11:46.043921+00:00 | 2022-08-02T09:11:46.043960+00:00 | 164 | false | ``` python\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n # To attack the king, maximal number of queens must be along 8 nearby closet block\n # Up/Down - Left/Right\n mapping = set(tuple(queen) for queen in queens)\n result = []\n for i, j in ((-1, 0), (1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1)):\n x, y = king\n while 0 <= x < 8 and 0 <= y < 8:\n x += i\n y += j\n if (x, y) in mapping:\n result.append((x, y))\n break\n return result\n``` | 2 | 0 | [] | 0 |
queens-that-can-attack-the-king | With 1 Function Only || Constant time and space complexity | with-1-function-only-constant-time-and-s-4hqs | Please Upvote if you like this\n\n\n\nclass Solution {\npublic:\n bool board[8][8];\n void check(int i, int j, int x, int y, vector<int> &sub){ \n | kawanchaudhary | NORMAL | 2022-06-19T10:38:42.486730+00:00 | 2022-06-19T10:38:42.486759+00:00 | 110 | false | # Please Upvote if you like this\n\n\n```\nclass Solution {\npublic:\n bool board[8][8];\n void check(int i, int j, int x, int y, vector<int> &sub){ \n \n if(i < 0 || j < 0 || i >= 8 || j >= 8) return; \n \n if(board[i][j] == true){\n sub[0] = i;\n sub[1] = j;\n return;\n }\n \n check(i + x, j + y, x, y, sub); \n }\n \n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n vector<vector<int>> ans;\n memset(board, false, sizeof(board));\n \n for(int i=0; i<queens.size(); i++){\n int x = queens[i][0];\n int y = queens[i][1];\n board[x][y] = true;\n }\n \n int dir[8][2] = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};\n \n \n int i = king[0];\n int j = king[1];\n \n for(int v=0; v<8; v++){\n int x = dir[v][0];\n int y = dir[v][1];\n vector<int> sub(2, -1);\n check(i+x, j+y, x, y, sub);\n \n if(sub[0] != -1){ \n ans.push_back(sub);\n }\n } \n \n return ans;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
queens-that-can-attack-the-king | C++ Chk in all 8 directions of King || Shorter and Clean Code | c-chk-in-all-8-directions-of-king-shorte-il8g | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king){\n \n vector<vector<int>> | dee_stroyer | NORMAL | 2022-04-25T05:08:33.562019+00:00 | 2022-04-25T05:08:33.562056+00:00 | 177 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king){\n \n vector<vector<int>>ans;\n //up down left right drup drdn dlup dldn\n vector<int>dx = {-1,1,0,0,-1,1,-1,1};\n vector<int>dy = {0,0,-1,1,1,1,-1,-1};\n \n vector<vector<int>>board(8,vector<int>(8,0));\n for(int i = 0; i<queens.size(); i++){\n board[queens[i][0]][queens[i][1]] = 1; \n }\n \n for(int i = 0; i<8; i++){\n \n int kr = king[0];\n int kc = king[1];\n \n while(kr<8 and kr>=0 and kc<8 and kc>=0){\n if(board[kr][kc] == 1){\n ans.push_back({kr,kc});\n break;\n }\n kr+=dx[i];\n kc+=dy[i];\n }\n }\n \n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 1 |
queens-that-can-attack-the-king | 81% intuitive python | 81-intuitive-python-by-abdullahalazaidy-4r3f | permutating all directions away from king except the [0,0]\n\n2. going though them , being within the chessboard and finding the first attacker -> breaking \n\n | abdullahalazaidy | NORMAL | 2020-11-09T00:57:08.925273+00:00 | 2020-11-09T00:57:46.946976+00:00 | 219 | false | 1. permutating all directions away from king except the [0,0]\n\n2. going though them , being within the chessboard and finding the first attacker -> breaking \n\n3. if found append to results \n\n81%\n```\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n """\n :type queens: List[List[int]]\n :type king: List[int]\n :rtype: List[List[int]]\n """\n \n di = [-1,0,1]\n \n rs =[]\n \n for i in di:\n for j in di:\n if (i==0 and j==0):\n continue\n \n nx = king[0] + i\n ny = king[1] + j\n \n \n while nx<8 and ny<8 and nx>-1 and ny>-1:\n \n \n if [nx,ny] in queens:\n rs.append([nx,ny])\n break\n nx += i\n ny += j \n \n continue \n \n return rs \n \n\n \n``` | 2 | 0 | ['Python', 'Python3'] | 1 |
queens-that-can-attack-the-king | [Java] Check 8 steps, general approach, helpful in different questions | java-check-8-steps-general-approach-help-2t80 | \nclass Solution {\n int[][] directions = new int[][]{{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};\n \n public List<List<Integer>> queensAtt | shailpanchal2005 | NORMAL | 2020-07-24T04:08:15.917296+00:00 | 2020-07-24T04:09:43.502660+00:00 | 115 | false | ```\nclass Solution {\n int[][] directions = new int[][]{{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};\n \n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n boolean[][] seen = new boolean[8][8];\n for( int[] queen : queens ) seen[queen[0]][queen[1]] = true; \n dfs(result, seen, king);\n return result;\n }\n \n public void dfs(List<List<Integer>> list,boolean[][] seen, int[] king ){ \n for(int[] dir : directions){\n for(int i = king[0], j = king[1] ; i >= 0 && i < 8 && j >= 0 && j <8 ; i = i+dir[0], j = j+dir[1] ){\n if( seen[i][j]){\n list.add(Arrays.asList(i,j));\n break;\n }\n }\n }\n }\n}\n```\n\n\nSame approach can be applied to https://leetcode.com/problems/available-captures-for-rook/\n```\nclass Solution { \n public int numRookCaptures(char[][] board) {\n for( int i = 0; i < 8; i++){\n for(int j = 0 ; j < 8;j++){\n if(board[i][j] == \'R\'){\n return dfs(board,i,j);\n }\n }\n }\n return -1;\n }\n \n public int dfs(char[][] board, int row,int column){\n int res = 0;\n int[][] directions = {{1,0}, {-1,0}, {0,1},{0,-1}};\n \n for( int[] dir : directions ){\n for( int i = row, j = column; i>= 0 && i < 8 && j >=0 && j < 8; i = i+dir[0], j = j+dir[1]){\n if( board[i][j] == \'p\'){\n res++;\n break;\n }\n else if( board[i][j] == \'B\'){\n break;\n }\n }\n }\n return res;\n }\n}\n``` | 2 | 0 | [] | 1 |
queens-that-can-attack-the-king | c++ | backtracking | N-queens like solution | simple | c-backtracking-n-queens-like-solution-si-1rsk | \nclass Solution {\npublic:\n bool isSafe(int x,int y)\n {\n if(x>=0 && y>=0 && x<8 && y<8)\n return true;\n return false;\n } | viking21 | NORMAL | 2020-06-30T17:29:46.253027+00:00 | 2020-06-30T17:29:46.253062+00:00 | 201 | false | ```\nclass Solution {\npublic:\n bool isSafe(int x,int y)\n {\n if(x>=0 && y>=0 && x<8 && y<8)\n return true;\n return false;\n }\n void findQueen(vector<vector<int>>& res,int moveX,int moveY,int x,int y,int arr[8][8])\n {\n if(isSafe(x,y))\n {\n if(arr[x][y])\n {\n vector<int> q={x,y};\n res.push_back(q);\n return;\n }\n findQueen(res,moveX,moveY,x+moveX,y+moveY,arr);\n }\n }\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> res;\n int arr[8][8]={0};\n for (auto q:queens)\n {\n arr[q[0]][q[1]]=1;\n }\n vector<int> moveX={-1,-1,-1,0,1,1,1,0};\n vector<int> moveY={-1,0,1,1,1,0,-1,-1};\n for(int i=0;i<8;i++)\n { \n findQueen(res,moveX[i],moveY[i],king[0]+moveX[i],king[1]+moveY[i],arr);\n }\n return res;\n } \n};\n``` | 2 | 0 | ['Backtracking', 'C'] | 0 |
queens-that-can-attack-the-king | Python: Check 8 directions, concise solution. 99.81% fast, 100% less memory usage | python-check-8-directions-concise-soluti-psf5 | \ndef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n\tdef attack(x, y, dx, dy):\n\t\twhile 0 <= x < 8 and 0 <= y < 8: | yashashreesuresh | NORMAL | 2020-01-29T05:29:03.209646+00:00 | 2020-01-29T05:32:48.329025+00:00 | 147 | false | ```\ndef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n\tdef attack(x, y, dx, dy):\n\t\twhile 0 <= x < 8 and 0 <= y < 8:\n\t\t\tx += dx; y += dy\n\t\t\tif (x, y) in queens: result.append([x, y]); return\n \n\tqueens = set(map(tuple, queens))\n result = []\n for dx, dy in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]: attack(king[0], king[1], dx, dy)\n return result\n``` | 2 | 0 | [] | 0 |
queens-that-can-attack-the-king | 4ms c++ | 4ms-c-by-cut_me_half-xbem | \nclass Solution {\npublic:\n int rows = 8;\n int cols = 8;\n int kx, ky;\n vector<vector<int>> ans;\n \n \n vector<vector<int>> queensAtta | cut_me_half | NORMAL | 2019-10-16T07:10:29.364981+00:00 | 2019-10-16T07:10:29.365034+00:00 | 216 | false | ```\nclass Solution {\npublic:\n int rows = 8;\n int cols = 8;\n int kx, ky;\n vector<vector<int>> ans;\n \n \n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n kx = king[0];\n ky = king[1];\n\n vector<vector<bool>> pos(64, vector<bool>(64));\n for(auto co: queens)\n {\n int x = co[0]; int y = co[1];\n pos[x][y] = true; \n }\n \n vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}, {0, 1}, {0, -1}};\n \n \n for(auto d : dirs)\n {\n for(int i = kx+d[0], j = ky+d[1]; i >= 0 && i < 64 && j >= 0 && j < 64; i += d[0], j+=d[1])\n {\n if(pos[i][j])\n {\n ans.push_back({i, j});\n break;\n }\n }\n }\n return ans;\n \n }\n};\n``` | 2 | 0 | [] | 0 |
queens-that-can-attack-the-king | Python, interview quality, 20 ms beats 94.2% | python-interview-quality-20-ms-beats-942-lscb | In my experience, interviewers are looking for this type of solution.\nLooping through the input list is O(n), and no other loops are used.\nThe only the best m | deleted_user | NORMAL | 2019-10-15T07:04:28.112347+00:00 | 2019-10-15T13:44:03.935294+00:00 | 245 | false | In my experience, interviewers are looking for this type of solution.\nLooping through the input list is O(n), and no other loops are used.\nThe only the best match in each direction is stored in memory.\n\nIt\'s worth stepping back from leetcode contests for a moment, and asking\nif the code you\'re writing would be viewed favorably in an interview.\nEven the best solutions, during a contest, tend to use variables that\nare only one letter long, and do not describe their purpose. Those are\nquick to write under time pressure, but they do not look good during\nan interview. If other people can\'t read your code easily, it costs\ntime, effort and confusion. It looks bad in an interview.\n\nSo I don\'t always follow that approach myself, but here I\'ve tried\nto use good variable names, O(n) time, and O(n) space.\n```python\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n # initial minimum distance must be greater than 7+7 (farthest diagonal)\n best_dist = { (x,y) : 15 for x in [-1,0,1] for y in [-1,0,1]}\n best_queens = {}\n king_x, king_y = king\n\n for queen in queens:\n queen_x, queen_y = queen\n\n # raw diff can be neative, but distance will be positive\n x_diff, y_diff = queen_x - king_x, queen_y - king_y\n x_dist, y_dist = abs(x_diff), abs(y_diff)\n if x_dist and y_dist and x_dist != y_dist:\n # no shared row, and not on a a diagonal\n continue\n\n # avoid (1//0) by using (0 and 1//0), which evaluates to 0.\n dist = x_dist + y_dist\n direction = (x_diff and x_diff//x_dist, y_diff and y_diff//y_dist)\n if dist < best_dist[direction]:\n # closest to king so far, in this direction.\n best_dist[direction] = dist\n best_queens[direction] = queen\n\n return best_queens.values()\n``` | 2 | 1 | ['Python'] | 1 |
queens-that-can-attack-the-king | JavaScript 100% fast, 100% space recursive solution. | javascript-100-fast-100-space-recursive-4y2s0 | It is easy to understand.\n```\nvar queensAttacktheKing = function(queens, king) {\n let output = [];\n let dirs = [[-1,0],[0,-1],[0,1],[1,0],[-1,-1],[-1,1],[ | yyoon | NORMAL | 2019-10-14T01:30:52.786812+00:00 | 2019-10-14T01:30:52.786886+00:00 | 178 | false | It is easy to understand.\n```\nvar queensAttacktheKing = function(queens, king) {\n let output = [];\n let dirs = [[-1,0],[0,-1],[0,1],[1,0],[-1,-1],[-1,1],[1,-1],[1,1]];\n\n const check = (position, dir) => {\n position[0] += dir[0];\n position[1] += dir[1];\n if (position[0] >= 0 && position[0] < 8 && position[1] >= 0 && position[1] < 8) {\n const found = queens.find(q => q[0] === position[0] && q[1] === position[1]);\n if (found) output.push(found);\n else check(position, dir);\n }\n };\n\n dirs.forEach(d => {\n check([king[0],king[1]], d); \n });\n\n return output;\n}; | 2 | 0 | [] | 0 |
queens-that-can-attack-the-king | BAD coding but still works | bad-coding-but-still-works-by-jatinyadav-d0el | \npublic static List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> queen = new LinkedList<>();\n List<Lis | jatinyadav96 | NORMAL | 2019-10-13T04:19:05.931667+00:00 | 2019-10-13T04:19:05.931713+00:00 | 152 | false | ```\npublic static List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> queen = new LinkedList<>();\n List<List<Integer>> result = new ArrayList<>();\n for (int[] a : queens) {\n List<Integer> ans = new ArrayList<>();\n ans.add(a[0]);\n ans.add(a[1]);\n queen.add(ans);\n }\n int x = king[0];\n int y = king[1];\n for (int i = x; i < 8; i++) {\n List<Integer> temp = new ArrayList<>();\n temp.add(i);\n temp.add(y);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n for (int i = x; i >= 0; i--) {\n List<Integer> temp = new ArrayList<>();\n temp.add(i);\n temp.add(y);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n\n for (int i = y; i < 8; i++) {\n List<Integer> temp = new ArrayList<>();\n temp.add(x);\n temp.add(i);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n for (int i = y; i >= 0; i--) {\n List<Integer> temp = new ArrayList<>();\n temp.add(x);\n temp.add(i);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n\n for (int i = 0; i < 8; i++) {\n List<Integer> temp = new ArrayList<>();\n temp.add(x + i);\n temp.add(y + i);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n for (int i = 1; i < 8; i++) {//\n List<Integer> temp = new ArrayList<>();\n temp.add(x - i);\n temp.add(y - i);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n\n for (int i = 0; i < 8; i++) {\n List<Integer> temp = new ArrayList<>();\n temp.add(x + i);\n temp.add(y - i);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n for (int i = 0; i < 8; i++) {\n List<Integer> temp = new ArrayList<>();\n temp.add(x - i);\n temp.add(y + i);\n if (queen.contains(temp)) {\n result.add(temp);\n break;\n }\n }\n\n return result;\n }\n```\n\nCan anyone tell me complexity of this code | 2 | 1 | [] | 0 |
queens-that-can-attack-the-king | Python, 15 line solution, uses 100% less memory than others | python-15-line-solution-uses-100-less-me-59ek | Queens can move in 8 directions, so I start at the king\'s location and move in every direction until I either find a queen or reach the edge of the board.\n\nc | deleted_user | NORMAL | 2019-10-13T04:14:08.000806+00:00 | 2019-10-13T04:14:08.000841+00:00 | 135 | false | Queens can move in 8 directions, so I start at the king\'s location and move in every direction until I either find a queen or reach the edge of the board.\n```\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n queens_dict = { (x,y): 1 for x,y in queens }\n directions = [ [-1,0], [1,0], [0,-1], [0,1],\n [-1,-1], [1,1], [-1,1], [1,-1] ]\n queens = []\n for xd,yd in directions:\n x,y = king\n while 0 <= x < 8 and 0 <= y < 8:\n x += xd\n y += yd\n if (x,y) in queens_dict:\n queens.append([x, y])\n break\n return queens\n``` | 2 | 2 | ['Python'] | 2 |
queens-that-can-attack-the-king | Java: a BFS on the king in 8 different directions (keep queens in a set) O(N) | java-a-bfs-on-the-king-in-8-different-di-jds3 | Keep track of all queen positons in a set so then you will know if your curr position is a queen. \nA BFS on the king in 8 different directions when you meet a | qwerjkl112 | NORMAL | 2019-10-13T04:05:24.634119+00:00 | 2019-10-13T04:32:26.609488+00:00 | 436 | false | Keep track of all queen positons in a set so then you will know if your curr position is a queen. \nA BFS on the king in 8 different directions when you meet a queen, stop there. \n\n```\nclass Solution {\n private final int[][] moves = new int[][] {{0, 1}, {1, 0}, {1, 1}, {-1, 0}, {0,-1}, {-1,-1}, {-1, 1}, {1, -1}};\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> res = new ArrayList<>();\n Set<Integer> queensP = new HashSet<>();\n for (int[] queen : queens) {\n queensP.add(queen[0]*9+queen[1]);\n }\n Deque<int[]> queue = new ArrayDeque<>();\n for (int[] move : moves) {\n queue.offer(new int[] {king[0], king[1], move[0], move[1]});\n }\n \n while (!queue.isEmpty()) {\n int[] curr = queue.poll();\n int x = curr[0];\n int y = curr[1];\n int move_x = curr[2];\n int move_y = curr[3];\n if (x < 0 || x > 8 || y < 0 || y >= 8) continue;\n if (queensP.contains(x*9+y)) {\n res.add(new ArrayList<>(Arrays.asList(x, y)));\n continue;\n } \n \n queue.offer(new int[] {x+move_x, y+move_y, move_x, move_y});\n }\n \n return res;\n }\n}\n``` | 2 | 0 | [] | 2 |
queens-that-can-attack-the-king | Better than 100%(Checking in all 8 directions) | better-than-100checking-in-all-8-directi-sidi | IntuitionApproachComplexity
Time complexity:
O(8*8)
Space complexity:
O(1)
Code | priyanshusaxena_07 | NORMAL | 2025-02-27T05:22:09.487308+00:00 | 2025-02-27T05:22:09.487308+00:00 | 40 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(8*8)
- Space complexity:
- O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens,
vector<int>& king) {
vector<vector<int>> board(8, vector<int>(8, -2));
board[king[0]][king[1]] = 1;
for (auto q : queens) {
board[q[0]][q[1]] = 0;
}
int i = king[0], j = king[1];
while (i >= 0) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
i--;
}
i = king[0], j = king[1];
while (i < 8) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
i++;
}
i = king[0], j = king[1];
while (j < 8) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
j++;
}
i = king[0], j = king[1];
while (j >= 0) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
j--;
}
i = king[0], j = king[1];
while (i < 8 and j < 8) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
j++, i++;
}
i = king[0], j = king[1];
while (j >= 0 and i >= 0) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
j--, i--;
}
i = king[0], j = king[1];
while (j >= 0 and i < 8) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
j--, i++;
}
i = king[0], j = king[1];
while (j < 8 and i >= 0) {
if (board[i][j] == 0) {
board[i][j] = -1;
break;
}
j++, i--;
}
vector<vector<int>> ans;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == -1)
ans.push_back({i, j});
}
}
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
queens-that-can-attack-the-king | easy solution | easy-solution-by-uongsuadaubung-twhr | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | uongsuadaubung | NORMAL | 2024-06-25T08:32:13.142667+00:00 | 2024-06-25T08:32:13.142698+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunction queensAttacktheKing(queens: number[][], king: number[]): number[][] {\n const result: number[][] = [];\n const findTheQueens = ( direction: number[]) => {\n let [x, y] = king;\n while (x >= 0 && x < 8 && y >= 0 && y < 8) {\n x += direction[0];\n y += direction[1];\n if (queens.some(quinn => quinn[0] === x && quinn[1] === y)) {\n result.push([x, y]);\n break;\n }\n }\n };\n for (let i = -1; i <= 1; i++) {\n for (let j = -1; j <= 1; j++) {\n if (i !== 0 || j !== 0) {\n findTheQueens([i,j]); //from king move 8 directions to find the queens\n }\n }\n }\n return result;\n};\n``` | 1 | 0 | ['TypeScript'] | 0 |
queens-that-can-attack-the-king | Java Solution beats 100% of Submissions | java-solution-beats-100-of-submissions-b-v514 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe best way to solve this problem is by recursivly scanning all 8 directions of the ki | mummysboy | NORMAL | 2024-05-15T01:35:58.595209+00:00 | 2024-05-15T01:35:58.595240+00:00 | 27 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe best way to solve this problem is by recursivly scanning all 8 directions of the king until we have either found a queen or reached the end of the board.\n\n\n\n\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize our chess board\n2. Create a helper function to check a specific direction\n3. Create a boolean helper function to check we are within the board\n4. Check all possible directions\n5. return our ArrayList\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(q) where q is the number of queens on the board\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) we use the same size board for each scenario\n# Code\n```\nclass Solution {\n // List to store the positions of queens that can attack the king\n List<List<Integer>> ans = new ArrayList<>();\n // 8x8 chess board\n int[][] board;\n\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n // Initialize the board\n board = new int[8][8];\n\n // Place queens on the board\n for (int[] queen : queens) {\n board[queen[0]][queen[1]] = 1;\n }\n\n // Check all eight possible directions\n checkDirection(king, -1, 0); // Top\n checkDirection(king, 1, 0); // Bottom\n checkDirection(king, 0, -1); // Left\n checkDirection(king, 0, 1); // Right\n checkDirection(king, -1, -1); // Top-left\n checkDirection(king, -1, 1); // Top-right\n checkDirection(king, 1, -1); // Bottom-left\n checkDirection(king, 1, 1); // Bottom-right\n\n return ans;\n }\n\n // Helper method to check a specific direction\n private void checkDirection(int[] king, int rowDir, int colDir) {\n int row = king[0];\n int col = king[1];\n\n while (isValid(row, col)) {\n row +=rowDir;\n col += colDir;\n\n if (isValid(row, col) && board[row][col] == 1) {\n // Queen found in this direction\n List<Integer> temp = new ArrayList<>();\n temp.add(row);\n temp.add(col);\n ans.add(temp);\n return;\n }\n }\n }\n\n // Helper method to check if a position is within the board limits\n private boolean isValid(int row, int col) {\n return row >= 0 && row < 8 && col >= 0 && col < 8;\n }\n}\n\n``` | 1 | 0 | ['Java'] | 0 |
queens-that-can-attack-the-king | Python. Solution driven by configuration. Beats 80% | python-solution-driven-by-configuration-j04pt | Intuition\nThere are eight direction king can be attacked. rather than trace each queen\'s ability to hit king, we can define 8 traces starrting from king posit | dev_lvl_80 | NORMAL | 2024-03-22T00:14:35.874029+00:00 | 2024-03-22T00:14:35.874050+00:00 | 25 | false | # Intuition\nThere are eight direction king can be attacked. rather than trace each queen\'s ability to hit king, we can define 8 traces starrting from king position, like waive, and increase radious of wave on each ste.\nNot super optimal, but very elegant.\n\nPlease add your like\n\n# Approach\nSame as intuition, plus stop trace direction once we detect queen.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n directions = [\n [0,1], [1,0], [1,1],\n [0,-1], [-1,0],[-1,-1],\n [-1,1], [1,-1]\n ]\n \n # reformat queens positions\n qs = set( [f"{i}_{j}" for i, j in queens] )\n ret = []\n\n step = 1\n while directions:\n pos_to_remove = set()\n for pos, d in enumerate(directions):\n #print(step, d, directions)\n \n check_pos = [king[0]+ d[0]*step, king[1] + d[1]*step] \n # if check_pos outside board - remove it\n if not 8 >= check_pos[0] >= 0 or not 8 >= check_pos[1] >= 0: \n pos_to_remove.add(pos)\n #print(f"\\tout")\n elif f"{check_pos[0]}_{check_pos[1]}" in qs:\n #print(f"\\tmatch")\n pos_to_remove.add(pos)\n ret.append( check_pos )\n \n directions = [d for p, d in enumerate(directions) if not p in pos_to_remove]\n \n step+=1\n return ret\n``` | 1 | 0 | ['Python3'] | 0 |
queens-that-can-attack-the-king | ✅✅Beats 100% || 🚀🚀 Easiest Solution || 😊😊Be Motivated😊😊 || | beats-100-easiest-solution-be-motivated-u4k4x | Intuition\n\n # UPVOTE IF THIS HELPS YOU\n\n# Code\n\n#include <vector>\n\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector< | Hi_coders786 | NORMAL | 2024-02-08T17:28:09.194470+00:00 | 2024-02-08T17:28:09.194487+00:00 | 329 | false | # Intuition\n\n # UPVOTE IF THIS HELPS YOU\n\n# Code\n```\n#include <vector>\n\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& q, vector<int>& k) {\n vector<vector<int>> v(8,vector<int>(8, 0));\n int n = q.size();\n for (int i = 0; i < n; i++) {\n v[q[i][0]][q[i][1]] = 1;\n }\n vector<vector<int>> ans;\n int x = k[0];\n int y = k[1]; \n for (int i = -1; i <= 1; i++) {\n for (int j = -1; j <= 1; j++) {\n if (i == 0 && j == 0) continue; \n int row = x + i;\n int col = y + j; \n while (row >= 0 && row < 8 && col >= 0 && col < 8) {\n if (v[row][col] == 1) {\n ans.push_back(vector<int>{row, col});\n break;\n } \n row += i;\n col += j;\n }\n }\n } \n return ans;\n }\n};\n\n``` | 1 | 0 | ['Matrix', 'Simulation', 'C++'] | 0 |
queens-that-can-attack-the-king | C++ | Intuitive Solution | Beats 100% | Check 8 Directions | c-intuitive-solution-beats-100-check-8-d-urwp | Approach\nThe approach here was to create an 8 x 8 chessboard matrix vector board which will have all cells initialized to false in the beginning. I traverse th | Anuvab | NORMAL | 2023-05-29T06:09:24.478017+00:00 | 2023-06-21T16:28:19.491573+00:00 | 37 | false | # Approach\nThe approach here was to create an 8 x 8 chessboard matrix vector `board` which will have all cells initialized to `false` in the beginning. I traverse through all the index positions given in `queens` and put `true` at all the cells where queens are present.\n\nAfter that, I have utilized 8 For Loops to check for the 8 Directions. Every Loop statement starts at the position of the `king` on the board and looks for the first queen in that direction. On encountering the first `false` (i.e. **Presence** of the **first queen** in that direction which can and will attack), it adds that position to `canAttack` which will be eventually returned.\n\nWe check for the **first queen in every direction** because **every other queen in that direction will be blocked by that queen and therefore they cannot attack**. There can be **at most One attack** from every direction and therefore, the maximum number of attacking queens can be 8 (For one queen in each of the 8 directions).\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n // to store the chessboard situation\n vector<vector<bool>> board(8,vector<bool>(8,false));\n vector<vector<int>> canAttack; // to store the answer\n // put true at all queen indices\n for(auto it:queens)\n board[it[0]][it[1]]=true;\n int i=king[0],j=king[1];\n // checking above\n for(;i>=0;i--)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n i=king[0];\n // checking below\n for(;i<8;i++)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n i=king[0];\n // checking left side\n for(;j>=0;j--)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n j=king[1];\n // checking right side\n for(;j<8;j++)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n j=king[1];\n // checking upper-left diagonal\n for(;i>=0 && j>=0;i--,j--)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n i=king[0],j=king[1];\n // checking upper-right diagonal\n for(;i>=0 && j<8;i--,j++)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n i=king[0],j=king[1];\n // checking lower-left diagonal\n for(;i<8 && j>=0;i++,j--)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n i=king[0],j=king[1];\n // checking lower-right diagonal\n for(;i<8 && j<8;i++,j++)\n if(board[i][j]){\n canAttack.push_back({i,j});\n break;\n }\n return(canAttack);\n }\n};\n```\n# P.S.\nAll sorts of constructive feedback are welcome in the comments. Share and Upvote if helpful. | 1 | 0 | ['Matrix', 'Simulation', 'C++'] | 0 |
queens-that-can-attack-the-king | queens ♛ Attacks King ♚ | queens-attacks-king-by-saeed20359-7wny | Intuition\n- This code is a Java implementation of a solution to the Queens That Can Attack the King problem on LeetCode. The problem involves finding all the q | saeed20359 | NORMAL | 2023-02-23T18:34:30.524206+00:00 | 2023-02-23T18:34:30.524239+00:00 | 32 | false | # Intuition\n- This code is a Java implementation of a solution to the `Queens That Can Attack the King` problem on `LeetCode`. The problem involves finding all the queens on a chessboard that can attack a given king.\n\n# Complexity\n- **Time complexity:**\nThe time complexity of this code is `O(q)`, where `q` is the number of queens. The for loop that iterates over the queens takes `O(q)` time. The inline and NearMore methods both have constant time complexity, so the total time complexity of the algorithm is dominated by the for loop. The worst-case scenario is when all queens are in line with the king, which requires checking all `q` queens. Therefore, the overall time complexity is `O(q)`.\n\n- **Space complexity:**\nThe space complexity of this code is `O(1)` since it only uses a fixed amount of memory to store the indexes array, `dy`, `dx`, and index variables. The number of queens and the king\'s position are given as inputs, but they are not used to allocate memory dynamically. The lists variable used to store the result has a maximum length of `8`, which is the maximum number of queens that can attack the king.\n\n# Code\n- This line declares the `queensAttacktheKing` method, which takes two inputs: an array of queen positions `queens` and the position of the king `king`. The method returns a list of positions of queens that can attack the king.\n``` java\npublic List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king)\n```\n- This line initializes the indexes array to `-1` for all eight directions (up-left, up, up-right, right, down-right, down, down-left, left).\n``` java\nint[] indexes = new int[]{-1, -1, -1, -1, -1, -1, -1, -1};\n```\n- These lines declare three integer variables to be used in the loop.\n``` java\nint dy, dx, index;\n```\n- This line starts a loop that iterates over all the queens on the board.\n``` java\nfor (int i = 0; i < queens.length; i++)\n```\n- This line checks if the current queen is in the same row, column, or diagonal as the king. The `inline` method is called to check this.\n``` java\nif (inline(queens[i], king))\n```\n- These lines calculate the vertical and horizontal distances between the `queen` and the `king`.\n``` java\ndy = king[1] - queens[i][1];\ndx = king[0] - queens[i][0];\n```\n- These lines calculate the `index` of the `indexes` array for the direction of the `queen` relative to the `king`. If the `queen` is in the same row, the `index` will be `7` or `3`. If the `queen` is in the same column, the `index` will be `1` or `5`. If the `queen` is in a diagonal direction, the `index` will be `0`, `2`, `4`, or `6`.\n``` java\n/* \n up-left -> 0, \n up -> 1, \n up-right -> 2, \n right -> 3, \n down-right -> 4, \n down -> 5, \n down-left -> 6, \n left -> 7\n*/\nif (dx == 0) index = dy < 0 ? 1 : 5;\nelse if (dy == 0) index = dx < 0 ? 7 : 3;\nelse if (dy < 0) index = dx < 0 ? 0 : 2;\nelse index = dx < 0 ? 6 : 4;\n```\n- This line updates the `indexes` array if the current `queen` is closer to the `king` in the given direction than the previous `queen` (if any) in that direction. The `NearMore` method is called to check this.\n\n``` java\nif (indexes[index] == -1 || NearMore(queens[i], queens[indexes[index]], king)) indexes[index] = i;\n```\n- Finally, this block of code creates a list of `queen` positions from the `indexes` array and returns it.\n``` java\nList<List<Integer>> lists = new ArrayList<>();\nfor (int i : indexes) if (i != -1) lists.add(Arrays.asList(queens[i][0], queens[i][1]));\nreturn lists;\n```\n- The `inline` method checks whether two pairs of coordinates are in the same row, column, or diagonal, by checking whether their x-coordinates are equal, their y-coordinates are equal, or the absolute difference of their x-coordinates equals the absolute difference of their y-coordinates, respectively.\n``` java\npublic boolean inline(int[] pair1, int[] pair2) {\n return\n pair1[0] == pair2[0] || // case row eq\n pair1[1] == pair2[1] || // case col eq\n Math.abs(pair1[1] - pair2[1]) == Math.abs(pair1[0] - pair2[0]); // case cross\n}\n```\n- The `NearMore` method checks which of `two pairs` of coordinates is closer to a target pair of coordinates. If the `two pairs` have the same x-coordinate (i.e., they are in the same row), it returns true if the absolute difference of their y-coordinates to the target is less than the corresponding difference of the other pair. Similarly, if the two pairs have the same y-coordinate (i.e., they are in the same column), it returns true if the absolute difference of their x-coordinates to the target is less than the corresponding difference of the other pair. If neither of these conditions hold, it returns `true` if the distance of the first pair from the target is `less than` the distance of the second pair from the target.\n``` java\npublic boolean NearMore(int[] pair1, int[] pair2, int[] target) {\n // case raw\n if (pair1[0] == pair2[0]) return Math.abs(target[1] - pair1[1]) < Math.abs(target[1] - pair2[1]);\n // case column\n if (pair1[1] == pair2[1]) return Math.abs(target[0] - pair1[0]) < Math.abs(target[0] - pair2[0]);\n // case cross\n return // dy_1^2 + dx_1^2 < dy_2^2 + dx_2^2\n Math.pow(target[1] - pair1[1], 2) + Math.pow(target[0] - pair1[0], 2) <\n Math.pow(target[1] - pair2[1], 2) + Math.pow(target[0] - pair2[0], 2);\n}\n```\n# Full Code\n``` java\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n // {\n // up-left -> 0, \n // up -> 1, \n // up-right -> 2, \n // right -> 3, \n // down-right -> 4, \n // down -> 5, \n // down-left -> 6, \n // left -> 7\n // } \n int[] indexes = new int[]{-1, -1, -1, -1, -1, -1, -1, -1};\n int dy, dx, index;\n for (int i = 0; i < queens.length; i++) {\n if (inline(queens[i], king)) // in line with king\n {\n dy = king[1] - queens[i][1];\n dx = king[0] - queens[i][0];\n // in column\n if (dx == 0) index = dy < 0 ? 1 /* up */ : 5 /* down */;\n // in row\n else if (dy == 0) index = dx < 0 ? 7 /* left */ : 3 /* right */;\n // cross-up\n else if (dy < 0) index = dx < 0 ? 0 /* up-left */ : 2 /* up-right */;\n // cross-down\n else index = dx < 0 ? 6 /* down-left */ : 4 /* down-right */;\n if (indexes[index] == -1 || NearMore(queens[i], queens[indexes[index]], king)) indexes[index] = i;\n }\n }\n // setup result\n List<List<Integer>> lists = new ArrayList<>();\n for (int i : indexes) if (i != -1) lists.add(Arrays.asList(queens[i][0], queens[i][1]));\n return lists;\n }\n\n public boolean inline(int[] pair1, int[] pair2) {\n return\n pair1[0] == pair2[0] || // case row eq\n pair1[1] == pair2[1] || // case col eq\n Math.abs(pair1[1] - pair2[1]) == Math.abs(pair1[0] - pair2[0]); // case cross\n }\n\n public boolean NearMore(int[] pair1, int[] pair2, int[] target) {\n // case raw\n if (pair1[0] == pair2[0]) return Math.abs(target[1] - pair1[1]) < Math.abs(target[1] - pair2[1]);\n // case column\n if (pair1[1] == pair2[1]) return Math.abs(target[0] - pair1[0]) < Math.abs(target[0] - pair2[0]);\n // case cross\n return // dy_1^2 + dx_1^2 < dy_0^2 + dx_0^2\n Math.pow(target[1] - pair1[1], 2) + Math.pow(target[0] - pair1[0], 2) <\n Math.pow(target[1] - pair2[1], 2) + Math.pow(target[0] - pair2[0], 2);\n }\n}\n```\n\n\n | 1 | 0 | ['Array', 'Math', 'Java'] | 0 |
queens-that-can-attack-the-king | python || easy to understand || with comments || begineer friendly | python-easy-to-understand-with-comments-mgdsq | \nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n board = [[\'\' for i in range(8)] fo | mohitsatija | NORMAL | 2023-01-17T11:50:12.858556+00:00 | 2023-01-17T11:50:12.858602+00:00 | 652 | false | ```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n board = [[\'\' for i in range(8)] for j in range(8)]\n ans = []\n \n # marking queens position on board\n for queen in queens:\n board[queen[0]][queen[1]] = \'Q\'\n \n # marking kings position on board\n board[king[0]][king[1]] = \'K\'\n \n for queen in queens:\n # function to check if a queen can target to king on board or not\n if self.canTarget(queen,king,board):\n ans.append(queen)\n return ans\n \n \n \n def canTarget(self,queen,king,board):\n q_x,q_y = queen[0],queen[1]\n \n # right side\n for i in range(q_y+1,8):\n if board[q_x][i] == \'K\':\n return True\n elif board[q_x][i] == \'Q\':\n break\n \n # left side\n for i in range(q_y-1,-1,-1):\n if board[q_x][i] == \'K\':\n return True\n elif board[q_x][i] == \'Q\':\n break\n \n # lower side\n for i in range(q_x+1,8):\n if board[i][q_y] == \'K\':\n return True\n elif board[i][q_y] == \'Q\':\n break\n \n # upper side\n for i in range(q_x-1,-1,-1):\n if board[i][q_y] == \'K\':\n return True\n elif board[i][q_y] == \'Q\':\n break\n \n # right down diagonal\n i,j = q_x+1,q_y+1\n while i<8 and j<8:\n if board[i][j] == \'K\':\n return True\n elif board[i][j] == \'Q\':\n break\n i += 1\n j += 1\n \n # left down diagonal\n i,j = q_x+1,q_y-1\n while i<8 and j>=0:\n if board[i][j] == \'K\':\n return True\n elif board[i][j] == \'Q\':\n break\n i += 1\n j -= 1\n \n # right up diagonal\n i,j = q_x-1,q_y+1\n while i>=0 and j<8:\n if board[i][j] == \'K\':\n return True\n elif board[i][j] == \'Q\':\n break\n i -= 1\n j += 1\n \n # left up diagonal\n i,j = q_x-1,q_y-1\n while i>=0 and j>=0:\n if board[i][j] == \'K\':\n return True\n elif board[i][j] == \'Q\':\n break\n i -= 1\n j -= 1\n \n # otherwise\n return False\n``` | 1 | 0 | ['Python', 'Python3'] | 1 |
queens-that-can-attack-the-king | C# | Tuple | c-tuple-by-c_4less-ev0x | \n# Code\n\npublic class Solution {\n public IList<IList<int>> QueensAttacktheKing(int[][] queens, int[] king) {\n IList<IList<int>> result = new List | c_4less | NORMAL | 2023-01-05T12:18:49.915579+00:00 | 2023-01-05T12:18:49.915625+00:00 | 43 | false | \n# Code\n```\npublic class Solution {\n public IList<IList<int>> QueensAttacktheKing(int[][] queens, int[] king) {\n IList<IList<int>> result = new List<IList<int>>();\n HashSet<(int,int)> queensPosition = new();\n\n foreach(int[] queen in queens)\n queensPosition.Add((queen[0], queen[1]));\n\n List<int[]> directions = new() { new int[]{-1,0}, new int[]{0,1 }, new int[]{1,0 }, new int[]{0,-1 },\n new int[]{-1,1}, new int[]{1,1 }, new int[]{-1,-1 }, new int[]{1,-1 } \n }; \n\n foreach(var direction in directions)\n {\n int newX = king[0] + direction[0];\n int newY = king[1] + direction[1];\n\n while(newX >= 0 && newY >= 0 && newX < 8 && newY < 8)\n {\n if(queensPosition.Contains((newX,newY)))\n {\n result.Add(new List<int>(){ newX, newY});\n break;\n }\n newX += direction[0];\n newY += direction[1];\n }\n\n }\n return result;\n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
queens-that-can-attack-the-king | ✅ O(1) || [Java / C++] || General logic for 8 directions move || The Main Intuition || | o1-java-c-general-logic-for-8-directions-8k03 | Intuition\n Describe your first thoughts on how to solve this problem. \n1. Check 8 directions around the King.\n2. Find the nearest queen in each direction.\n\ | Sayakmondal | NORMAL | 2022-10-14T14:12:35.682917+00:00 | 2022-10-14T14:12:47.694235+00:00 | 85 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Check 8 directions around the King.\n2. Find the nearest queen in each direction.\n\n\n# Complexity\n- Time complexity: $$O(8*8)$$ ~ $$O(1 )$$\nIf it is a general matrix then T.C - $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(8*8)$$ ~ $$O(1)$$\nIf it is a general matrix then for seen array S.C - $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```\nif(you like)\n\tplease please UPVOTE\uD83D\uDE0A\uD83D\uDE0A;\n```\n\n`Please read the comment in the code carefully then you will undersatnd everything.`\n\n# Java Code\n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n boolean[][] seen = new boolean[8][8];\n for (int[] queen : queens) seen[queen[0]][queen[1]] = true; // Mark seen where the queen is present\n\n // This nested loop will generate all 8 directions. \n for (int dx = -1; dx <=1; dx++) {\n for (int dy = -1; dy <=1; dy++) {\n if (dx == 0 && dy == 0) continue; // means the position where the king is present so no need to go inside.\n int x = king[0], y = king[1];\n while (x + dx >= 0 && x + dx < 8 && y + dy >= 0 && y + dy < 8) // Check the new position if it is inside the chessboard boundary.\n {\n x += dx;\n y += dy;\n if (seen[x][y]) // We reach one of the queens position so this quuen will attack\n { \n result.add(Arrays.asList(x, y));\n break; // This direction is complete try other direction.\n }\n }\n }\n }\n return result;\n }\n}\n```\n# C++ Code\n```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> result;\n bool seen[8][8];\n memset(seen, false, sizeof(seen));\n for (vector<int> queen : queens) seen[queen[0]][queen[1]] = true; // Mark the positions seen where the queens are present\n\n // This nested loop will generate all 8 directions. \n for (int dx = -1; dx <=1; dx++) \n {\n for (int dy = -1; dy <=1; dy++) \n {\n if (dx == 0 && dy == 0) continue; // means the position where the king is present so no need to inside.\n\n int x = king[0], y = king[1];\n while (x + dx >= 0 && x + dx < 8 && y + dy >= 0 && y + dy < 8) // Check the new position if it is inside the chessboard boundary.\n {\n x += dx; // New position of x in that particular direction\n y += dy; // New position of y in that particular direction\n if (seen[x][y]) // We reach one of the queens position in that particular direction so this queen will attack the king\n { \n vector<int> temp;\n temp.push_back(x);\n temp.push_back(y);\n result.push_back(temp);\n temp.clear();\n break; // This direction is complete try other direction.\n }\n }\n }\n }\n return result;\n }\n};\n```\n\n | 1 | 0 | ['Array', 'Matrix', 'Simulation', 'C++', 'Java'] | 0 |
queens-that-can-attack-the-king | Java Solution | With Explanation | java-solution-with-explanation-by-tbekpr-qpzd | \n```\nclass Solution {\n public List> queensAttacktheKing(int[][] queens, int[] king) {\n List> result = new ArrayList<>();\n Set set = new Ha | tbekpro | NORMAL | 2022-09-13T17:39:16.544985+00:00 | 2022-09-13T17:39:16.545027+00:00 | 353 | false | \n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n Set<String> set = new HashSet<>();\n\t\t//putting queens coordinates into hash as a string\n for (int i = 0; i < queens.length; i++) {\n set.add(queens[i][0] + "" + queens[i][1]);\n }\n //up, up/right, right, down/right, down, left/down, left, up/left\n int[][] directions = new int[][]{{-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}};\n\t\t//going on each direction and when meet first queen, then add to result and break\n\t\t//moving towards that direction\n for (int i = 0; i < directions.length; i++) {\n int y = king[0], x = king[1];\n y += directions[i][0];\n x += directions[i][1];\n while (cellExists(y, x, 8, 8)) {\n if (set.contains(y + "" + x)) {\n List<Integer> list = new ArrayList<>();\n list.add(y);\n list.add(x);\n result.add(list);\n break;\n }\n y += directions[i][0];\n x += directions[i][1];\n }\n }\n return result;\n }\n \n private boolean cellExists(int row, int col, int rows, int cols) {\n return (row <= rows - 1 && row >= 0) && (col <= cols - 1 && col >= 0);\n }\n} | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | Python solution | dfs from king | python-solution-dfs-from-king-by-vincent-x7vg | \ndef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n\tqueens = set(tuple(q) for q in queens)\n\tdirs = [[-1, 0], [1, | vincent_great | NORMAL | 2022-09-08T07:54:29.083745+00:00 | 2022-09-08T07:55:25.186720+00:00 | 234 | false | ```\ndef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n\tqueens = set(tuple(q) for q in queens)\n\tdirs = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]]\n\tans = []\n\tfor dx, dy in dirs:\n\t\tx, y = king\n\t\twhile(0<=x<8 and 0<=y<8):\n\t\t\tx += dx\n\t\t\ty += dy\n\t\t\tif (x, y) in queens:\n\t\t\t\tans.append([x, y])\n\t\t\t\tbreak\n\treturn ans\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | C++ Simple Naive Approach | c-simple-naive-approach-by-sneha34-h79z | ```\nvector> queensAttacktheKing(vector>& queens, vector& king) {\n vector> qn(8,vector(8,0)),ans;\n \n for(int i=0;i=0;i--)\n {\n | Sneha34 | NORMAL | 2022-08-16T06:38:47.792997+00:00 | 2022-08-16T06:38:47.793039+00:00 | 371 | false | ```\nvector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> qn(8,vector<int>(8,0)),ans;\n \n for(int i=0;i<queens.size();i++)\n {\n qn[queens[i][0]][queens[i][1]]=1;\n }\n //same col towards up\n for(int i=king[0]-1;i>=0;i--)\n {\n if(qn[i][king[1]])\n {\n ans.push_back({i,king[1]});\n break;\n }\n }\n //same col towards down\n for(int i=king[0]+1;i<8;i++)\n {\n if(qn[i][king[1]])\n {\n ans.push_back({i,king[1]});\n break;\n }\n }\n //same row towards left\n for(int i=king[1]-1;i>=0;i--)\n {\n if(qn[king[0]][i])\n {\n ans.push_back({king[0],i});\n break;\n }\n }\n //same row towards right\n for(int i=king[1]+1;i<8;i++)\n {\n if(qn[king[0]][i])\n {\n ans.push_back({king[0],i});\n break;\n }\n }\n //top left\n int j=king[1];\n for(int i=king[0];i>=0 && j>=0;i--)\n {\n if(qn[i][j])\n {\n ans.push_back({i,j});\n break;\n }\n j--;\n }\n //bottom right\n j=king[1];\n for(int i=king[0];i<8 && j<8;i++)\n {\n if(qn[i][j])\n {\n ans.push_back({i,j});\n break;\n }\n j++;\n }\n //top right\n j=king[1];\n for(int i=king[0];i>=0 && j<8;i--)\n {\n if(qn[i][j])\n {\n ans.push_back({i,j});\n break;\n }\n j++;\n }\n //bottom left\n j=king[1];\n for(int i=king[0];i<8 && j>=0;i++)\n {\n if(qn[i][j])\n {\n ans.push_back({i,j});\n break;\n }\n j--;\n }\n \n return ans;\n \n } | 1 | 0 | ['C'] | 0 |
queens-that-can-attack-the-king | C++ | Easy Understanding | Clean and Concise | Well Explained | c-easy-understanding-clean-and-concise-w-7l5t | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> ans;\n | rudrakshh | NORMAL | 2022-07-29T18:43:28.351349+00:00 | 2022-07-29T18:43:28.351411+00:00 | 65 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> ans;\n int queenPosition[8][8] = {}; // here we intialise all elements to 0, if we do not initialise then array is filled with garbage value\n for(auto& q : queens) queenPosition[q[0]][q[1]] = 1; // storing the queen positions, where the queen are present are filled with 1 and all others are 0\n \n vector<int> dirs = {-1, 0, 1}; // by using this vector we easily trace 8 directions without writing enough line of code\n for(int dx : dirs) {\n for(int dy : dirs) {\n if(dx == 0 && dy == 0) continue;\n int x = king[0], y = king[1];\n while(x + dx >= 0 && x + dx < 8 && y + dy >= 0 && y + dy < 8) {\n x += dx, y += dy;\n if(queenPosition[x][y]) {\n ans.push_back({x, y}); // if garbage value is present then for every (row, column), if condition is true and our answer will contain extra or different (row, column)\n break;\n }\n }\n }\n }\n \n return ans;\n }\n};\n\n\n``` | 1 | 1 | ['Array', 'C', 'Matrix', 'Simulation'] | 0 |
queens-that-can-attack-the-king | Java | BFS | java-bfs-by-parth13-nykb | Run a bfs from king in all 8 directions. When a queen is detected stop bfs in that direction.\nInstead of a char array we can also use hashmap to check wether q | parth13 | NORMAL | 2022-06-09T05:42:17.470244+00:00 | 2022-06-09T05:42:17.470292+00:00 | 178 | false | Run a bfs from king in all 8 directions. When a queen is detected stop bfs in that direction.\nInstead of a char array we can also use hashmap to check wether queen exist on that coordinate or not.\n```\nclass Solution {\n public class Pair{\n int x;\n int y;\n int dir;\n public Pair(int x,int y,int dir){\n this.x = x;\n this.y = y;\n this.dir = dir;\n }\n }\n public int[] rdir = {-1,-1,0,1,1,1,0,-1};\n public int[] cdir = {0,-1,-1,-1,0,1,1,1};\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> ans = new ArrayList<>();\n char[][] board = new char[8][8];\n for(int i=0;i<8;i++){\n for(int j=0;j<8;j++){\n board[i][j] = \'.\';\n }\n }\n for(int[] arr:queens){\n int x = arr[0];\n int y = arr[1];\n board[x][y] = \'Q\';\n }\n Queue<Pair> qu = new ArrayDeque<>();\n for(int i=0;i<8;i++){\n int x = king[0];\n int y = king[1];\n qu.add(new Pair(x,y,i));\n }\n //bfs\n while(qu.size()>0){\n Pair rem = qu.remove();\n //queen check\n if(board[rem.x][rem.y] == \'Q\'){\n List<Integer> subans = new ArrayList<>();\n subans.add(rem.x);\n subans.add(rem.y);\n ans.add(subans);\n continue;\n }else{\n int nx = rem.x + rdir[rem.dir];\n int ny = rem.y + cdir[rem.dir];\n if(nx>=0 && nx<8 && ny>=0 && ny<8){\n qu.add(new Pair(nx,ny,rem.dir));\n }\n }\n \n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Breadth-First Search', 'Java'] | 0 |
queens-that-can-attack-the-king | C++ || 100% faster || 93% space efficient | c-100-faster-93-space-efficient-by-kusha-9sij | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n int x=king[0];\n int | kushagra3010 | NORMAL | 2022-05-03T10:46:24.726147+00:00 | 2022-05-03T10:46:24.726175+00:00 | 140 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n int x=king[0];\n int y=king[1];\n \n vector<vector<int>> ans;\n \n int a[8][8];\n memset(a,0,sizeof(a));\n \n for(int i=0;i<queens.size();i++)\n {\n a[queens[i][0]][queens[i][1]]=1;\n }\n \n a[x][y]=2;\n \n for(int i=y+1;i<8;i++)\n {\n if(a[x][i]==1)\n {\n ans.push_back({x,i});\n break;\n }\n }\n \n for(int i=y-1;i>=0;i--)\n {\n if(a[x][i]==1)\n {\n ans.push_back({x,i});\n break;\n }\n }\n \n for(int i=x+1;i<8;i++)\n {\n if(a[i][y]==1)\n {\n ans.push_back({i,y});\n break;\n }\n }\n \n for(int i=x-1;i>=0;i--)\n {\n if(a[i][y]==1)\n {\n ans.push_back({i,y});\n break;\n }\n }\n \n int i=x+1,j=y+1;\n while(i<8 and j<8)\n {\n if(a[i][j]==1)\n {\n ans.push_back({i,j});\n break;\n }\n ++i;\n ++j;\n }\n \n i=x+1,j=y-1;\n while(i<8 and j>=0)\n {\n if(a[i][j]==1)\n {\n ans.push_back({i,j});\n break;\n }\n ++i;\n --j;\n }\n \n i=x-1,j=y-1;\n while(i>=0 and j>=0)\n {\n if(a[i][j]==1)\n {\n ans.push_back({i,j});\n break;\n }\n --i;\n --j;\n }\n \n i=x-1,j=y+1;\n while(i>=0 and j<8)\n {\n if(a[i][j]==1)\n {\n ans.push_back({i,j});\n break;\n }\n --i;\n ++j;\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | 100% Faster CPP - BruteForce OP | 100-faster-cpp-bruteforce-op-by-divyansh-zlh1 | \n\nvector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n\t\t// All eight directions stored \n vector<pair<int,int> | Divyansh-- | NORMAL | 2022-04-21T07:39:45.299714+00:00 | 2022-04-21T07:39:45.299747+00:00 | 124 | false | ```\n\nvector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n\t\t// All eight directions stored \n vector<pair<int,int>> dir = {{0,1},{1,0},{-1,0},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1}};\n\t\t// res vectore will sotre our result\n vector<vector<int>> res;\n\t\t// we make a 2d board to create the simulation for our traversal\n vector<vector<bool>> board(8,vector<bool>(8,false));\n\t\t// mark all the queens present of the board as true\n for(auto& x: queens)\n {\n board[x[0]][x[1]]=true;\n }\n\t\t// take each coordinate and traverse\n for(auto& [x,y] : dir)\n {\n int ki = king[0];\n int kj = king[1];\n\t\t\t// traverse till path in valid and when you get your first queen break\n while(ki>=0 && kj>=0 && ki<8 && kj<8 && board[ki][kj]==false)\n {\n ki+=x;\n kj+=y;\n }\n\t\t\t// if you get a queen then coordinate would definately be valid so push them in res vector\n if(ki>=0 && kj>=0 && ki<8 && kj<8)\n res.push_back({ki,kj});\n }\n\t\t// return the answer\n return res;\n }\n\n``` | 1 | 0 | ['C', 'C++'] | 0 |
queens-that-can-attack-the-king | ☑✅ JAVA || Easy to Understand || Simple Approach | java-easy-to-understand-simple-approach-8xbdn | The approach is to create an array of 8 * 8 and mark the queens as 1.\nChecking all 8 directions around the King.\nFinding the nearest queen in each direction a | mohit0178 | NORMAL | 2022-04-12T11:17:13.716068+00:00 | 2022-04-12T11:17:13.716095+00:00 | 101 | false | The approach is to create an array of 8 * 8 and mark the queens as 1.\nChecking all 8 directions around the King.\nFinding the nearest queen in each direction and add the coordinate of that queen in answer.\n\n```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int[][] chess = new int[8][8];\n \n for(int[] queen : queens){\n int x = queen[0];\n int y = queen[1];\n chess[x][y] = 1;\n }\n \n List<List<Integer>> ans = new ArrayList<>();\n int x = king[0]; // x coordinate of king\n int y = king[1]; // y coordinate of king\n \n // checking column left to king\n for(int j = y - 1; j >= 0; j--){\n if(chess[x][j] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(x);\n list.add(j);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking column right to king\n for(int j = y + 1; j < 8; j++){\n if(chess[x][j] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(x);\n list.add(j);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking row above the king\n for(int i = x - 1; i >= 0; i--){\n if(chess[i][y] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(i);\n list.add(y);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking row below the king\n for(int i = x + 1; i < 8; i++){\n if(chess[i][y] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(i);\n list.add(y);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking left diagonal above the king\n for(int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--, j--){\n if(chess[i][j] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(i);\n list.add(j);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking left diagonal below the king\n for(int i = x + 1, j = y + 1; i < 8 && j < 8; i++, j++){\n if(chess[i][j] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(i);\n list.add(j);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking right diagonal above the king\n for(int i = x - 1, j = y + 1; i >= 0 && j < 8; i--, j++){\n if(chess[i][j] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(i);\n list.add(j);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n // checking right diagonal below the king\n for(int i = x + 1, j = y - 1; i < 8 && j >= 0; i++, j--){\n if(chess[i][j] == 1){\n List<Integer> list = new ArrayList<>();\n list.add(i);\n list.add(j);\n ans.add(new ArrayList<>(list));\n break;\n }\n }\n \n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
queens-that-can-attack-the-king | Traverse in all 8 directions from the King | traverse-in-all-8-directions-from-the-ki-u4no | A queen can only attack the king if it\'s in the same row/column/diagonal of the king, and also no other queen should be in it\'s way. Hence we will traverse in | viking05 | NORMAL | 2022-03-15T13:21:17.984821+00:00 | 2022-03-15T13:21:17.984866+00:00 | 82 | false | A queen can only attack the king if it\'s in the same row/column/diagonal of the king, and also no other queen should be in it\'s way. Hence we will traverse in all 8 directions from the king\'s coordinates and if we find a queen, then add it to the list and stop checking for that direction (only the first encountered queen in a particular direction can attack the king). There can be at most 8 queens that can attack the king.\n\n```\nclass Solution \n{\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] k) \n {\n List<List<Integer>> dangerousQueens = new ArrayList<>();\n boolean[][] isQueen = new boolean[8][8];\n for(int[] q: queens)\n isQueen[q[0]][q[1]] = true;\n int[] dx = {1, -1, 0, 0, 1, -1, 1, -1};\n int[] dy = {0, 0, 1, -1, 1, 1, -1, -1};\n for(int i=0; i<8; i++)\n {\n int x = k[0];\n int y = k[1];\n while(x >= 0 && x < 8 && y >= 0 && y < 8)\n {\n x += dx[i];\n y += dy[i];\n if(x < 0 || x >= 8 || y < 0 || y >= 8)\n break;\n if(isQueen[x][y])\n {\n List<Integer> q = new ArrayList<>();\n q.add(x);\n q.add(y);\n dangerousQueens.add(q);\n break;\n }\n }\n }\n return dangerousQueens;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
queens-that-can-attack-the-king | C++ | Basic | Draw lines of attack from the king until you hit a queen | c-basic-draw-lines-of-attack-from-the-ki-7l40 | ```\nclass Solution {\npublic:\n vector> queensAttacktheKing(vector>& queens, vector& king) \n {\n vector> dirs = {\n {1, 0},\n | JaiKapoor | NORMAL | 2022-02-17T10:34:32.808035+00:00 | 2022-02-17T10:34:32.808060+00:00 | 109 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) \n {\n vector<pair<int, int>> dirs = {\n {1, 0},\n {1, 1},\n {0, 1},\n {-1, 1},\n {-1, 0},\n {-1, -1},\n {0, -1},\n {1, -1}\n };\n vector<vector<int>> result;\n \n vector<vector<bool>> board(8, vector<bool>(8));\n \n for(auto& queen : queens)\n {\n board[queen[0]][queen[1]] = true;\n }\n \n for(auto [x, y] : dirs)\n {\n int ni = king[0];\n int nj = king[1];\n \n while(ni >= 0 and ni < 8 and nj >= 0 and nj < 8 and not board[ni][nj])\n {\n ni += x;\n nj += y;\n }\n if(ni >= 0 and ni < 8 and nj >= 0 and nj < 8)\n {\n result.push_back({ni, nj});\n }\n }\n \n return result;\n }\n}; | 1 | 0 | ['Backtracking', 'C'] | 0 |
queens-that-can-attack-the-king | From a kings perspective | from-a-kings-perspective-by-sasipriyan-vxn7 | Idea is to see from kings perspective. Steps as follows\n Start from kings position\n Walk straight in x axis, y axis and diagnol\n If we meet a queen, add that | sasipriyan | NORMAL | 2022-02-11T04:10:26.318220+00:00 | 2022-02-11T04:18:21.942538+00:00 | 68 | false | Idea is to see from kings perspective. Steps as follows\n* Start from kings position\n* Walk straight in x axis, y axis and diagnol\n* If we meet a queen, add that to result and return\n* Return if we reach the end of the chessboard\n```\nclass Solution:\n def dfs(self, x, y, visited,dim):\n if visited[x][y] ==\'Q\':\n self.ans.append([x,y])\n return\n k = dim[0]+x\n l = dim[1]+y\n if k >= 0 and l >= 0 and k < 8 and l < 8:\n self.dfs(k,l, visited,dim)\n \n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n self.dims = [[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,-1],[1,-1],[-1,1]]\n visited = [[False for i in range(8)] for j in range(8)]\n for q in queens:\n visited[q[0]][q[1]] = \'Q\'\n self.ans = []\n for dim in self.dims:\n k = king[0]+dim[0]\n l = king[1]+dim[1]\n if k>= 0 and l>= 0 and k < 8 and l < 8 :\n self.dfs(king[0],king[1],visited, dim)\n return self.ans\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | [Python3] BFS without repeating cells | python3-bfs-without-repeating-cells-by-n-ugrt | \nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n res=[]\n x,y=king\n ar | nuno-dev1 | NORMAL | 2022-01-07T11:05:49.423025+00:00 | 2022-01-07T11:16:40.781485+00:00 | 68 | false | ```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n res=[]\n x,y=king\n arr=[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)]\n queens=set(tuple(el) for el in queens)\n deque=collections.deque()\n for el in arr:\n deque.append((x+el[0],y+el[1],el))\n while deque:\n x,y,increment=deque.popleft()\n if 0<=x<8 and 0<=y<8:\n if (x,y) in queens:\n res.append([x,y])\n continue\n addX,addY=increment\n deque.append((x+addX,y+addY,increment))\n return res\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | C++, Simple Naive Solution, No Rocket Science | c-simple-naive-solution-no-rocket-scienc-zfko | class Solution {\n# public:\n vector> queensAttacktheKing(vector>& queens, vector& king) {\n vector> ans;\n map,bool> m;\n for(auto it : | nishant34_ | NORMAL | 2021-11-23T16:39:32.749908+00:00 | 2021-11-23T16:39:32.749950+00:00 | 77 | false | # class Solution {\n# public:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>> ans;\n map<pair<int,int>,bool> m;\n for(auto it : queens)\n m[{it[0],it[1]}]=true;\n int kr=king[0],kc=king[1];\n // top\n for(int i=kr-1; i>=0; i--){\n if(m.find({i,kc})!=m.end()){\n ans.push_back({i,kc});\n break;\n }\n }\n //bottom\n for(int i=kr+1; i<8; i++){\n if(m.find({i,kc})!=m.end()){\n ans.push_back({i,kc});\n break;\n }\n }\n //left\n for(int i=kc-1; i>=0; i--){\n if(m.find({kr,i})!=m.end()){\n ans.push_back({kr,i});\n break;\n }\n }\n //right\n for(int i=kc+1; i<8; i++){\n if(m.find({kr,i})!=m.end()){\n ans.push_back({kr,i});\n break;\n }\n }\n //top left\n int i=kr-1,j=kc-1;\n while(i>=0 && j>=0){\n if(m.find({i,j})!=m.end()){\n ans.push_back({i,j});\n break;\n }\n i--; j--;\n }\n //bottom right\n i=kr+1,j=kc+1;\n while(i<8 && j<8){\n if(m.find({i,j})!=m.end()){\n ans.push_back({i,j});\n break;\n }\n i++; j++;\n }\n //top right\n i=kr-1,j=kc+1;\n while(i>=0 && j<8){\n if(m.find({i,j})!=m.end()){\n ans.push_back({i,j});\n break;\n }\n i--; j++;\n }\n //bottom left\n i=kr+1,j=kc-1;\n while(i<8 && j>=0){\n if(m.find({i,j})!=m.end()){\n ans.push_back({i,j});\n break;\n }\n i++; j--;\n }\n return ans;\n }\n}; | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | [Python] beats 94%, simple and easy to understand | python-beats-94-simple-and-easy-to-under-t9no | \nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n def checkDirection(direction, ans): | Sol-cito | NORMAL | 2021-10-26T15:22:30.602655+00:00 | 2021-10-26T15:28:28.172927+00:00 | 94 | false | ```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n def checkDirection(direction, ans): # move the king to each direction\n x, y = king[0], king[1]\n while 0 <= x < 9 and 0 <= y < 9:\n if [x, y] in queens: # when encountering a queen, mark the location and return\n ans.append([x, y])\n return\n x += direction[0]\n y += direction[1]\n\n ans = []\n for direction in [1, 0], [0, 1], [-1, 0], [0, -1], [-1, -1], [1, 1], [1, -1], [-1, 1]:\n checkDirection(direction, ans)\n return ans\n```\n\t\t\nSo the point is, we just move the king (not the queen!) to each direction until it meets a queen. \n\nWhen it happens, simply add its location and return. | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | Simple Code in Python | simple-code-in-python-by-kinglucifer-tl6n | \n```\n#Searching with respet to king as he is the target\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[ | Kinglucifer | NORMAL | 2021-08-11T04:18:58.879789+00:00 | 2021-08-11T04:18:58.879868+00:00 | 81 | false | \n```\n#Searching with respet to king as he is the target\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans = []\n chess = [[0 for i in range(8)] for j in range(8)]\n #marking queens\n for i in queens:\n chess[i[0]][i[1]] = 1\n """\n left : [-1,0],\n right: [1,0],\n up: [0,-1],\n down: [0,1],\n top-left: [-1,-1],\n top-right: [1,-1],\n bottom-left: [-1,1],\n bottom-right: [1,1]\n """\n directions = [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1], [-1,1],[1,1]]\n for i in directions:\n kx,ky = king[0]+i[0], king[1]+i[1]\n while kx in range(8) and ky in range(8):\n if chess[kx][ky] == 1:\n ans.append([kx,ky])\n break\n kx = kx + i[0]\n ky = ky + i[1]\n return ans\n | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | Python faster than 100% | python-faster-than-100-by-akki2790-hcaa | The comments in the code are self explanatory. Here\'s a brief overview:\n1) Build a grid of size 8x8\n2) Populate the grid with queens\n3) Traverse in all 8 di | akki2790 | NORMAL | 2021-08-08T10:17:14.799482+00:00 | 2021-08-08T10:17:14.799514+00:00 | 124 | false | The comments in the code are self explanatory. Here\'s a brief overview:\n1) Build a grid of size 8x8\n2) Populate the grid with queens\n3) Traverse in all 8 directions, starting from the King\'s coordinates. When you encounter a Queen, update the count and don\'t go any further.\n\n\t\tclass Solution:\n\t\t\tdef queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n\t\t\t\t# build the grid\n\t\t\t\tgrid=[[None for c in range(8)] for r in range(8)]\n\t\t\t\tfor queen in queens:\n\t\t\t\t\tgrid[queen[0]][queen[1]]="Q"\n\t\t\t\tans=[]\n\t\t\t\trow,col=king\n\t\t\t\t# go up\n\t\t\t\tfor rowup in reversed(range(row)):\n\t\t\t\t\tif grid[rowup][col]=="Q":\n\t\t\t\t\t\tans.append([rowup,col])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go down\n\t\t\t\tfor rowdown in range(row+1,8):\n\t\t\t\t\tif grid[rowdown][col]=="Q":\n\t\t\t\t\t\tans.append([rowdown,col])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go left\n\t\t\t\tfor colleft in reversed(range(col)):\n\t\t\t\t\tif grid[row][colleft]=="Q":\n\t\t\t\t\t\tans.append([row,colleft])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go right\n\t\t\t\tfor colright in range(col+1,8):\n\t\t\t\t\tif grid[row][colright]=="Q":\n\t\t\t\t\t\tans.append([row,colright])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go diagonally up leftside\n\t\t\t\trowx,colx=king\n\t\t\t\twhile rowx>0 and colx>0:\n\t\t\t\t\trowx-=1\n\t\t\t\t\tcolx-=1\n\t\t\t\t\tif grid[rowx][colx]=="Q":\n\t\t\t\t\t\tans.append([rowx,colx])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go diagonally down rightside\n\t\t\t\trowx,colx=king\n\t\t\t\twhile rowx<7 and colx<7:\n\t\t\t\t\trowx+=1\n\t\t\t\t\tcolx+=1\n\t\t\t\t\tif grid[rowx][colx]=="Q":\n\t\t\t\t\t\tans.append([rowx,colx])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go diagonally up rightside\n\t\t\t\trowx,colx=king\n\t\t\t\twhile rowx>0 and colx<7:\n\t\t\t\t\trowx-=1\n\t\t\t\t\tcolx+=1\n\t\t\t\t\tif grid[rowx][colx]=="Q":\n\t\t\t\t\t\tans.append([rowx,colx])\n\t\t\t\t\t\tbreak\n\t\t\t\t# go diagonally down leftside\n\t\t\t\trowx,colx=king\n\t\t\t\twhile rowx<7 and colx>0:\n\t\t\t\t\trowx+=1\n\t\t\t\t\tcolx-=1\n\t\t\t\t\tif grid[rowx][colx]=="Q":\n\t\t\t\t\t\tans.append([rowx,colx])\n\t\t\t\t\t\tbreak\n\t\t\t\treturn ans | 1 | 1 | [] | 0 |
queens-that-can-attack-the-king | Java short|simple|fully commented Code | java-shortsimplefully-commented-code-by-0mmz0 | Complexity\n\nTime : As the size of chessboard is limited.\n\nFor the chessboard of N * N\nTime O(queens + 8N)\nSpace O(queens)\n\nJava Code :\n\n public Lis | vikas3110 | NORMAL | 2021-07-27T06:22:33.960366+00:00 | 2021-07-27T06:32:36.155155+00:00 | 95 | false | **Complexity**\n\nTime : As the size of chessboard is limited.\n\nFor the chessboard of N * N\nTime O(queens + 8N)\nSpace O(queens)\n\nJava Code :\n\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n \n List<List<Integer>> res = new ArrayList<>();//for storing results\n\t\t\n\t\t//direction array for checking in all 8 directions\n int[][] dir = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};\n \n\t\t//creating hashset of queens sitting position for checking whether Queen is present at any particular position or not\n HashSet<Integer> setofQueens= new HashSet<>();\n for(int i=0;i<queens.length;i++){\n int r=queens[i][0];\n int c=queens[i][1];\n\t\t\t\t// addrowsandcolumns by making it a 2 digitnumber MSB is for rows and LSB is for columns for eg [1,0] = 10 \n setofQueens.add(r*10+c); \n }\n \n //Algo Step 1 : Search For Attacking Queen from King\'s sitting position in all 8 possible chess baord directions \n\t //Algo Step 2 : Validate Queens Presence in Hashset & Store the nearest QueensAttacking as List \n int radius = 8;\n int r=king[0];\n int c=king[1];\n \n for(int d = 0; d < dir.length; d++){\n \n for(int rad = 1; rad < radius; rad++){\n int rr = r + (rad * dir[d][0]);\n int cc = c + (rad * dir[d][1]);\n\n if(rr >= 0 && rr < radius && cc >= 0 && cc < radius) { // for moving only in valid positions in the board\n if(setofQueens.contains((rr*10+cc)))\n {\n res.add(Arrays.asList(rr,cc));// adding the nearest attacking queen row and columns as list to rest ArrayList\n break;// breaking after finding just nearest queen\n } \n } \n }\n }\n \n return res; \n } | 1 | 0 | [] | 1 |
queens-that-can-attack-the-king | Checking in all 8 Directions | checking-in-all-8-directions-by-piyushbi-8oii | \nclass Solution {\npublic:\n bool isValid(int i,int j,int m,int n)\n {\n return i>=0 && j>=0 && i<m && j<n;\n }\n vector<vector<int>> queens | piyushbisht3 | NORMAL | 2021-07-20T17:18:41.175375+00:00 | 2021-07-20T17:18:41.175414+00:00 | 103 | false | ```\nclass Solution {\npublic:\n bool isValid(int i,int j,int m,int n)\n {\n return i>=0 && j>=0 && i<m && j<n;\n }\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n \n int kX=king[0],kY=king[1];\n \n int rows[8]={0,0,-1,+1,+1,-1,+1,-1}; //all directions coordinates\n int cols[8]={-1,+1,0,0,+1,-1,-1,+1};\n \n map<pair<int,int>,int>q;\n for(auto pts:queens)\n {\n q[{pts[0],pts[1]}]++;\n }\n vector<vector<int>>ans;\n for(int index=0;index<8;index++) //searching in all possible directions;\n {\n int i=kX,j=kY; \n \n while(isValid(i,j,8,8))\n {\n i+=rows[index];\n j+=cols[index];\n if(q.find({i,j})!=q.end())\n {\n ans.push_back({i,j});\n break;\n }\n }\n }\n return ans;\n \n }\n};\n``` | 1 | 0 | ['C'] | 0 |
queens-that-can-attack-the-king | Java Solution - Easy to Understand. | java-solution-easy-to-understand-by-rros-vvre | \nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n | rrosy2000 | NORMAL | 2021-07-05T11:34:33.259329+00:00 | 2021-07-05T11:34:33.259359+00:00 | 67 | false | ```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n List<List<Integer>> result = new ArrayList<>();\n //Looping through and keeping track of all the queens on the board\n boolean[][] board = new boolean[8][8];\n for(int i=0;i<queens.length;i++)\n board[queens[i][0]][queens[i][1]] = true;\n //All the directions in which the king can move.\n int[][] directions = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};\n int king_X = king[0];\n int king_Y = king[1];\n for(int i=0;i<directions.length;i++)\n {\n int x = directions[i][0];\n int dupX = x;\n int y = directions[i][1];\n int dupY = y;\n boolean found = false;\n \n while((king_X+x)>=0 && (king_X+x)<8 && (king_Y+y)>=0 && (king_Y+y)<8 && !found)\n {\n if(board[king_X+x][king_Y+y])\n {\n List<Integer> list = new ArrayList<>();\n list.add(king_X+x);\n list.add(king_Y+y);\n result.add(list);\n found = true;\n }\n x = x+dupX;\n y = y+dupY;\n }\n }\n return result;\n }\n}\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | 80% Faster C++ Solution | 80-faster-c-solution-by-krvinaykr27450-xkxo | \nclass Solution {\npublic:\n vector<vector<int>> res;\n \n void checkForQueen(int row,int col,int rowChange,int colChange,vector<vector<char>>& chess | krvinaykr27450 | NORMAL | 2021-06-27T18:00:19.852457+00:00 | 2021-06-27T18:00:19.852508+00:00 | 67 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> res;\n \n void checkForQueen(int row,int col,int rowChange,int colChange,vector<vector<char>>& chess)\n {\n if(row < 0 || col < 0 || row == 8 || col == 8)\n {\n return;\n }\n \n if(chess[row][col] == \'Q\')\n {\n vector<int> add;\n add.push_back(row);\n add.push_back(col);\n res.push_back(add);\n return;\n }else{\n checkForQueen(row+rowChange,col+colChange,rowChange,colChange,chess);\n }\n }\n \n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<char>> chess(8,vector<char> (8,\'.\'));\n chess[king[0]][king[1]] = \'K\';\n for(int i=0;i<queens.size();i++)\n {\n chess[queens[i][0]][queens[i][1]] = \'Q\';\n }\n \n checkForQueen(king[0],king[1],-1,0,chess);\n checkForQueen(king[0],king[1],1,0,chess);\n checkForQueen(king[0],king[1],-1,-1,chess);\n checkForQueen(king[0],king[1],-1,1,chess);\n checkForQueen(king[0],king[1],1,-1,chess);\n checkForQueen(king[0],king[1],1,1,chess);\n checkForQueen(king[0],king[1],0,-1,chess);\n checkForQueen(king[0],king[1],0,1,chess);\n \n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | Long a** solution but in 0ms | long-a-solution-but-in-0ms-by-chiragxaro-up7s | \nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n unordered_map<string,int> ma | chiragxarora | NORMAL | 2021-06-25T10:57:48.728534+00:00 | 2021-06-25T10:57:48.728565+00:00 | 53 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n unordered_map<string,int> map;\n vector<vector<int>> ans;\n for(int i=0;i<queens.size();i++){\n string s = to_string(queens[i][0]) + to_string(queens[i][1]);\n map[s] = 1;\n }\n int ki = king[0], kj = king[1];\n for(int i=ki-1;i>=0;i--) {\n string str = to_string(i) + to_string(kj);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(i);\n v.push_back(kj);\n ans.push_back(v);\n break;\n }\n }\n for(int i=ki+1;i<8;i++) {\n string str = to_string(i) + to_string(kj);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(i);\n v.push_back(kj);\n ans.push_back(v);\n break;\n }\n }\n for(int j=kj-1;j>=0;j--) {\n string str = to_string(ki) + to_string(j);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(ki);\n v.push_back(j);\n ans.push_back(v);\n break;\n }\n }\n for(int j=kj+1;j<8;j++) {\n string str = to_string(ki) + to_string(j);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(ki);\n v.push_back(j);\n ans.push_back(v);\n break;\n }\n }\n for(int i=ki+1,j=kj+1;i<8&&j<8;i++,j++){\n string str = to_string(i) + to_string(j);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(i);\n v.push_back(j);\n ans.push_back(v);\n break;\n }\n }\n for(int i=ki-1,j=kj-1;i>=0&&j>=0;i--,j--){\n string str = to_string(i) + to_string(j);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(i);\n v.push_back(j);\n ans.push_back(v);\n break;\n }\n }\n for(int i=ki-1,j=kj+1;i>=0&&j<8;i--,j++){\n string str = to_string(i) + to_string(j);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(i);\n v.push_back(j);\n ans.push_back(v);\n break;\n }\n }\n for(int i=ki+1,j=kj-1;i<8&&j>=0;i++,j--){\n string str = to_string(i) + to_string(j);\n if(map.find(str)!=map.end()){\n vector<int> v;\n v.push_back(i);\n v.push_back(j);\n ans.push_back(v);\n break;\n }\n }\n \n \n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | C++ very easy solution | c-very-easy-solution-by-coder_mnn-0sht | \n int x_move[8]={-1,-1,0,1,1,1,0,-1};\n int y_move[8]={0,1,1,1,0,-1,-1,-1};\n \n void check_attack(int pos, int chess[8][8], int x, int y, vector<v | coder_mnn | NORMAL | 2021-06-02T20:11:48.215524+00:00 | 2021-06-02T20:11:48.215555+00:00 | 144 | false | ```\n int x_move[8]={-1,-1,0,1,1,1,0,-1};\n int y_move[8]={0,1,1,1,0,-1,-1,-1};\n \n void check_attack(int pos, int chess[8][8], int x, int y, vector<vector<int>>&res){\n while(x>=0 && x<8 && y>=0 && y<8){\n if(chess[x][y]==1){\n vector<int>v;\n v.push_back(x);\n v.push_back(y);\n res.push_back(v);\n return;\n }\n x+=x_move[pos];\n y+=y_move[pos];\n }\n }\n \n vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n vector<vector<int>>res;\n int chess[8][8];\n memset(chess,0,sizeof(chess));\n for(int i=0;i<queens.size();i++)chess[queens[i][0]][queens[i][1]]++;\n for(int i=0;i<8;i++)check_attack(i,chess,king[0],king[1],res);\n return res;\n }\n``` | 1 | 4 | [] | 0 |
queens-that-can-attack-the-king | O(queens) Concise Solution for Unbounded Board | oqueens-concise-solution-for-unbounded-b-vhiz | Many current solutions exploit the fact of limited 8\xD78 board. However this problem can be easily extended to an unbounded board as a follow-up. In this case, | maristie | NORMAL | 2021-05-22T05:03:47.714855+00:00 | 2021-05-22T05:03:47.714886+00:00 | 62 | false | Many current solutions exploit the fact of limited 8\xD78 board. However this problem can be easily extended to an unbounded board as a follow-up. In this case, most current solutions will be invalidated, while other solutions are much too cumbersome to write.\n\nI\'d like to give a substantially shorter but versatile solution for this case.\n\n```java\nclass Solution {\n static final int[][] direcs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};\n \n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int[][] memo = new int[8][];\n for (int[] queen : queens) {\n int x = queen[0] - king[0];\n int y = queen[1] - king[1];\n \n for (int i = 0; i < 8; ++i) {\n int[] direc = direcs[i];\n if (x * direc[1] == y * direc[0] && x * direc[0] >= 0 && y * direc[1] >= 0) {\n if (memo[i] == null || distanceOf(king, memo[i]) > distanceOf(king, queen)) {\n memo[i] = queen;\n }\n }\n }\n }\n return Arrays.stream(memo)\n .filter(Objects::nonNull)\n .map(pair -> List.of(pair[0], pair[1]))\n .collect(Collectors.toList());\n }\n \n private int distanceOf(int[] p1, int[] p2) {\n return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);\n }\n}\n``` | 1 | 0 | [] | 0 |
queens-that-can-attack-the-king | 8 lines python code | 8-lines-python-code-by-2019csb1077-m0wo | \nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n attackingQueens = []; directions = [ | 2019csb1077 | NORMAL | 2021-05-19T11:54:01.308285+00:00 | 2021-05-19T11:54:01.308317+00:00 | 96 | false | ```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n attackingQueens = []; directions = [-1,0,1]\n for dx in directions:\n for dy in directions:\n if dx==dy==0: continue\n x,y = king\n while(0<=x+dx<8 and 0<=y+dy<8):\n x+=dx;y+=dy;if ([x,y] in queens):attackingQueens.append([x,y]);break\n return attackingQueens\n \n \n \n``` | 1 | 1 | [] | 0 |
queens-that-can-attack-the-king | Extremely Begineer friendly code in PYTHON | extremely-begineer-friendly-code-in-pyth-17bp | This is my first dicsussion submission post, and I wish it helps someone trying to understand this paticular problem. The approach I have used is not the most e | TanmayAgarwal | NORMAL | 2021-05-17T11:16:12.218982+00:00 | 2021-05-17T11:16:12.219023+00:00 | 127 | false | This is my first dicsussion submission post, and I wish it helps someone trying to understand this paticular problem. The approach I have used is not the most effcient approach and tbh there are some beautiful and much shorter approches to this problem already up. \n\nI took the time to write this post, to help someone who is not able to visualise the problem efficiently. The code is long, but its extremely concise and I have added explainaitions for each and every part without skipping anything. \n\nAny kind of feedback is much appreciated. \n\n\n```\n\nclass Solution(object):\n def queensAttacktheKing(self, queens, kings): # Note I have changed to input parameter from king to kings\n max_len, q = self.maxlength(queens, kings), [] # The function maxlength() returns the maximum number among the given list of queens and kings\n dp = self.FormBoard(queens, kings, max_len) # FormBoard() function retuns the board of size max_len * max_len\n for i in range(max_len +1):\n for j in range(max_len + 1):\n if dp[i][j] == "Q" and self.Solver(dp, i, j): # Whenever we encounter a queen on the board we call the Solver\n q.append([i, j]) # If the co-ordinates of the queen match all the criterias, they are appended in the queue \n return q # Return the Queue \n\n def Solver(self, dp, i, j):\n if i<0 or i>=len(dp) or j<0 or j>=len(dp[0]) or dp[i][j] != "Q":\n return False \n\n \'\'\' Now we check all the 8 directions. I have defined two funcitons for doing this task. The first function, CheckDirection, \n checks the four directions of Left, Right, Up and Down and the second function, CheckDiagonal, checks the four diagonals,\n Left_up(LU), Left_down(LD), Right_up(RU), and Right_down(RD). If any of the directions return a True, that means the paticular\n queen can attack the king and hence all the fuction calls are logically OR\'ed\'\'\'\n\n if self.CheckDirection(\'Left\', i, j, dp) or self.CheckDirection(\'Right\', i, j, dp) or \\\n self.CheckDirection(\'Up\', i, j, dp) or self.CheckDirection(\'Down\', i, j, dp) or \\\n self.CheckDiagonal(\'LU\', i, j, dp) or self.CheckDiagonal(\'LD\', i, j, dp) or \\\n self.CheckDiagonal(\'RD\', i, j, dp) or self.CheckDiagonal(\'RU\', i, j, dp) :\n return True\n # If all the directions return a False, the king cannot be attacked by the paticular queen and hence return False\n return False \n\n def CheckDirection(self, direction, row, col, dp):\n\n \'\'\' This function is used to check the four mainstream directions. The four directions are indexd into the dictionary\n \'direction_mapper\'. Next a queue is defined which holds the start, end, step and static variables of the for loop, for each \n paticular direction. What I mean by static here is the fact that, if our direction is Up or Down, we move through\n only the rows and hence the column remain static. Similarly, While moving Right or Left, we move along the columns \n and the row remains static. So, for each direction I have also added a static variable to signify which part(row or column)\n remains static while moving in a paticluar direction \'\'\'\n\n direction_mapper = {\'Left\' : 0, \'Right\' : 1, \'Up\' : 2, \'Down\' : 3}\n\n \'\'\' The bounds are as follows \n 1. Left : we start one column before the current column(at which the current queen is placed) and go till the first column. Hence, \n start = col -1, end = -1 (As end is -1, the for loop stops at 0), step = -1 (We are moving backwards), \n static = row (as we move through the columns)\n 2. Right : we start from the next column, of the current column and stop only if we reach the last column. Hence :\n start = col+1, end = len(dp[0]) (The last column), step = 1 ( We are moving forwards), static = row (column wise movement)\n 3. Up : we start from the previous row of the current row and move till the last row. Hence, \n start = row - 1, end = -1, step = -1 ( Moving backwards ), static = col (As we move through the rows)\n 4. Down : we start from the next row of the current row, and move till we reach the last row. hence \n start = row + 1, end = len(dp) (Which gives the last row), step = 1 (forward movement), static = col\'\'\'\n\n\n q = [(col-1, -1, -1, row), (col+1, len(dp[0]), 1, row), (row-1,-1, -1, col), (row+1, len(dp), 1, col)]\n start, end, step, static = q.pop( direction_mapper[ direction ])\n\n \'\'\' Now we reach the part where I have declared two flags : flag_queen and flag_king. At each iteration, if a queen is in our path, flag_queen is set to 1\n and if a king in in our path, flag_king is set to 1. NOTE : for a queen to successfully attack a king, it should encounter a king in its path, \n before it encounters any other queen. We keep this fact in our mind and at every point of the iteration, we check: IF flag_king is one( Which \n means we have encountered a king) AND flag_queen is zero ( which means we have not encountered a queen yet), the function returns True, or else False.\n This check of flags is performed by the CheckFlag() function\'\'\'\n\n\n flag_queen, flag_king = 0, 0\n if row == col:\n\n \'\'\' One non trivial thing which happens is when the row number = column number in the co-ordinates of the queen. During this time\n I had to explicitly define the loops to ensure that the static column or the row is choosen. This loop works the following way :\n if row number == column number, it checks the direction. If the direction is Up or Down, The column is set static. Else-If the \n direction is Left or Right, the row is set static\'\'\'\n\n if direction == \'Up\' or direction == \'Down\':\n for i in range(start, end, step):\n if dp[i][col] == "Q": \n flag_queen = 1 # If encountered Queen, flag_queen is set to 1\n elif dp[i][col] == "K":\n flag_king = 1 # If encountered King, flag_king is set to 2\n if self.CheckFlag(flag_queen, flag_king): # Function to check both the flags at every point \n return True \n elif direction == \'Left\' or direction ==\'Right\':\n for i in range(start, end, step):\n if dp[row][i] == "Q":\n flag_queen = 1\n elif dp[row][i] == "K":\n flag_king = 1\n if self.CheckFlag(flag_queen, flag_king):\n return True \n\n # This part is for when row number != Column Number\n\n elif static == row: \n for i in range(start, end, step):\n if dp[row][i] == "Q":\n flag_queen = 1\n elif dp[row][i] == "K":\n flag_king = 1\n if self.CheckFlag(flag_queen, flag_king):\n return True \n elif static == col:\n for i in range(start, end, step):\n if dp[i][col] == "Q":\n flag_queen = 1\n elif dp[i][col] == "K":\n flag_king = 1\n if self.CheckFlag(flag_queen, flag_king):\n return True \n return False \n\n def CheckDiagonal(self, direction, row, col, dp):\n\n \'\'\' Here we define the directions : Left_up (LU), Left_Down(LD), Right_Up(RU) and Right_Down(RD).\n Here we have 6 variables in each tuple of our queue. First off, there are total of 4 tuples in \n the queue referring to the four directions. Now each tuple contains : start, end, step, start1, end1, step1.\n The start, end, step is for the row and start1, end1, step1 is for the column. In a diagonal movement, neither the \n row nor the column remains static at any point hence we specify the ranges for both row and col\'\'\'\n\n direction_mapper = {\'LU\' : 0, \'LD\' : 1, \'RU\' : 2, \'RD\' : 3}\n\n \'\'\'The bounds are :\n\n 1. Left Up : The row starts from the previous row and ends at the first row with a negative one step \n and the column starts from the previous column, going till the first column with a negative step\n 2. Left Down : The row start from the next row and iterates till it reaches the final row which is (len(dp)) \n and the column starts from the previous column all the way to the first column with a negative step \n 3. Right Up : The row starts from the previous row and iterates all the way to the first, and the column starts from \n the next column all the way to the last \n 4. Right Down : The row starts from the next row, and the column too from the next column and they both end at the last\n row and column respectively \'\'\'\n\n\n\n q = [(row-1, -1, -1, col-1, -1, -1), (row+1, len(dp), 1, col-1, -1, -1), \\\n (row-1, -1, -1, col+1, len(dp[0]), 1), (row+1, len(dp), 1, col+1, len(dp[0]), 1)]\n start, end, step, start1, end1, step1 = q.pop( direction_mapper[direction] )\n flag_queen, flag_king = 0, 0 # Same idea as previous function \n\n for i, j in zip(range(start, end, step), range(start1, end1, step1)): #zip is used to iterate through both the specified counds of rows and cols Together\n if dp[i][j] == "Q":\n flag_queen = 1\n elif dp[i][j] == "K":\n flag_king = 1\n if self.CheckFlag(flag_queen, flag_king):\n return True\n return False\n\n def CheckFlag(self, flag_queen, flag_king): # Trivial defination\n if flag_queen == 0 and flag_king == 1:\n return True \n return False \n\n def maxlength(self, queens, kings): # This function returns the max number in the given lists \n length = 0 \n for queen in queens:\n length = max(length, queen[0], queen[1], kings[0], kings[1])\n return length \n\n def FormBoard(self, queens, kings, max_len): # This returns a board of size max_len * max_len \n dp = [[0 for _ in range(max_len+1)]for _ in range(max_len+1)]\n for queen in queens:\n dp[ queen[0] ][ queen[1] ] = \'Q\'\n dp[ kings[0] ][ kings[1] ] = \'K\'\n return dp \n\n\n```\n\nI Hope this explainaition was clear and concise. Thank you for checking it out. | 1 | 0 | ['Python'] | 0 |
queens-that-can-attack-the-king | JAVA | java-by-akshay3213-9rtj | \nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int minb0=Integer.MAX_VALUE,mina0=Integer.MAX_VALU | akshay3213 | NORMAL | 2021-05-15T08:13:30.790231+00:00 | 2021-05-15T08:13:30.790262+00:00 | 85 | false | ```\nclass Solution {\n public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n int minb0=Integer.MAX_VALUE,mina0=Integer.MAX_VALUE,minb1=Integer.MAX_VALUE,mina1=Integer.MAX_VALUE;\n int minRb=Integer.MAX_VALUE,minRa=Integer.MAX_VALUE,minLb=Integer.MAX_VALUE,minLa=Integer.MAX_VALUE;\n int arr[]=new int[8];\n for(int i=0;i<8;i++){\n arr[i]=queens.length;\n arr[i]=queens.length;\n }\n for(int i=0;i<queens.length;i++){\n if(king[0]==queens[i][0]){\n if(king[1]>queens[i][1]){\n if(king[1]-queens[i][1]<minb0){\n minb0=king[1]-queens[i][1];\n arr[0]=i;\n }\n }else{\n if(queens[i][1]-king[1]<mina0){\n mina0=queens[i][1]-king[1];\n arr[1]=i;\n }\n }\n }else if(king[1]==queens[i][1]){\n \n if(king[0]>queens[i][0]){\n if(king[0]-queens[i][0]<minb1){\n minb1=king[0]-queens[i][0];\n arr[2] =i;\n }\n }else{\n if(queens[i][0]-king[0]<mina1){\n mina1=queens[i][0]-king[0];\n arr[3]=i;\n }\n }\n }else if(king[1]-queens[i][1]==king[0]-queens[i][0]){\n if(king[0]>queens[i][0]){\n if(king[1]-queens[i][1]<minRb){\n minRb=king[1]-queens[i][1];\n arr[4]=i;\n }\n }else{\n if(queens[i][1]-king[1]<minRa){\n minRa=queens[i][1]-king[1];\n arr[5]=i;\n }\n }\n }else if(king[1]-queens[i][1]+king[0]-queens[i][0]==0){\n if(king[1]>queens[i][1]){\n if(king[1]-queens[i][1]<minLb){\n System.out.println(king[1]-queens[i][1]+" "+minLb);\n minLb=king[1]-queens[i][1];\n arr[6]=i;\n }\n }else{\n if(queens[i][1]-king[1]<minLa){\n minLa=queens[i][1]-king[1];\n arr[7]=i;\n }\n }\n }\n }\n List<List<Integer>> op=new ArrayList<List<Integer>>();\n for(int i=0;i<8;i++){\n List<Integer> temp=new ArrayList<Integer>();\n if(arr[i]<queens.length){\n temp.add(queens[arr[i]][0]);\n temp.add(queens[arr[i]][1]);\n op.add(temp);\n }\n }\n return op;\n }\n}\n``` | 1 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.