GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Other/safe_squares_rooks.py at master · hhy5277/coding-problems

Expand file tree

/

safe_squares_rooks.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
60 lines (45 loc) · 1.52 KB
/

safe_squares_rooks.py

Copy path

File metadata and controls

60 lines (45 loc) · 1.52 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'''
Safe Squares from Rooks
On a generalized n-by-n chessboard, there are some number of rooks, each rook represented as a
two-tuple (row, column) of the row and the column that it is in. (The rows and columns are
numbered from 0 to n-1.) A chess rook covers all squares that are in the same row or in the same
column as that rook. Given the board size n and the list of rooks on that board, count the number of
empty squares that are safe, that is, are not covered by any rook.
Input: [(1, 1), (3, 5), (7, 0), (7, 6)], 8
Output: 20
=========================================
The result is a multiplication between free rows and free columns.
Use hashsets to store the free rows and columns.
Time Complexity: O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
def safe_squares_rooks(rooks, n):
rows = set()
cols = set()
for i in range(n):
rows.add(i)
cols.add(i)
for rook in rooks:
if rook[0] in rows:
rows.remove(rook[0])
if rook[1] in cols:
cols.remove(rook[1])
return len(rows) * len(cols)
###########
# Testsing #
###########
# safe_squares_rooks 1
# Correct result => 1
print(safe_squares_rooks([(1, 1)], 2))
# safe_squares_rooks 2
# Correct result => 4
print(safe_squares_rooks([(2, 3), (0, 1)], 4))
# safe_squares_rooks 3
# Correct result => 20
print(safe_squares_rooks([(1, 1), (3, 5), (7, 0), (7, 6)], 8))
# safe_squares_rooks 4
# Correct result => 0
print(safe_squares_rooks([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], 6))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.