Problem:


Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

..#
#..
.#.
.#.
#.#



Sample input:
4 4
##.#
....
##.#
.#.#


Sample output:
###
###
.##

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
grid = []
for i in range(H):
  line = input()
  for i in range(len(line)):
    if line[i] == '#':
      grid.append(line)
      break
gridans = [[''] for i in range(len(grid))]
for i in range(W):
  flag = 0
  for j in range(len(grid)):
    if grid[j][i] == '#':
      flag = 1
  if flag == 1:
    for j in range(len(grid)):
      gridans[j][0] += grid[j][i]
for i in range(len(gridans)):
  print(gridans[i][0])

Submission status: Accepted

Solution code:
from sys import stdin
H, W = map(int, input().split())
A = []
for _ in range(H):
    A.append([x for x in input()])
AT = list(zip(*A))
tate = []
yoko = []

for i in range(H):
    if '#' in A[i]:
        tate.append(i)
for i in range(W):
    if '#' in AT[i]:
        yoko.append(i)

for i in tate:
    for j in yoko:
        print(A[i][j], end='')
    print('')

Submission status: Accepted

Solution code:
# coding: utf-8
H, W = map(int, input().split())
A = [list(input()) for _ in range(H)]
B = [[A[i][j] for i in range(H)] for j in range(W)]
check_H = sorted([i for i in range(H) if '#' not in A[i]], reverse=True)
check_W = sorted([i for i in range(W) if '#' not in B[i]], reverse=True)
for i in check_H:
    A = A[:i] + A[i + 1:]
for i in check_W:
    for j in range(len(A)):
        A[j] = A[j][:i] + A[j][i + 1:]
for a in A:
    print(''.join(a))

Submission status: Accepted

Solution code:
#ABC107 B
H,W = map(int,input().split(' '))
field = []

for i in range(H):
	field.append(str(input()))

def rotate(mat):
	#転置行列を返す関数
	mat_t = []
	if mat != []:
		for i in range(len(mat[0])):
			#matのいまの列数＝転置後の行数
			mat_t.append([])
		for i in range(len(mat[0])):
			#matを横方向に走査
			for j in range(len(mat)):
				#matを縦方向に走査
				mat_t[i] += mat[j][i]
		for i in range(len(mat_t)):
			mat_t[i] = ''.join(mat_t[i])
	return mat_t

def white(n):
	return '.' * n

while white(W) in field:
    field.remove(white(W))
field_t = rotate(field)
while white(len(field_t[0])) in field_t:
    field_t.remove(white(len(field_t[0])))
field_t_t = rotate(field_t)

for s in field_t_t:
	print(s)

Submission status: Accepted

Solution code:
H, W = map(int,input().split())
HW = [input() for _ in range(H)]
HW = ["".join(hw) for hw in zip(*HW) if hw.count("#") > 0]
HW = ["".join(hw) for hw in zip(*HW) if hw.count("#") > 0]
print("\n".join(HW))

Submission status: Accepted

Solution code:
from collections import Counter
H,W=map(int,input().split())
a=[list(str(input())) for i in range(H)]
b=[]
n_H=0
for l in a:
    c=Counter(l)
    if c['.']!=W:
        b.append(l)
        n_H+=1
d=[]
b=list(map(list,zip(*b)))
for l in b:
    c=Counter(l)
    if c['.']!=n_H:
        d.append(l)
d=list(map(list, zip(*d)))

for l in d:
    s=''.join(l)
    print(s)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a = [list(input()) for i in range(h)]

row = [False] * h
col = [False] * w

for i in range(h):
    for j in range(w):
        if a[i][j] == "#":
            row[i] = True
            col[j] = True

for i in range(h):
    if row[i]:
        for j in range(w):
            if col[j]:
                print(a[i][j], end = "")#改行しない
        print()#改行

Submission status: Accepted

Solution code:
#S=input()
#N=int(input())
H,W=map(int,input().split())
a=[]
for i in range(H):
    ai=input()
    if ai=="."*W:
        continue
    a.append(ai)
h=len(a)
def tenti(a):
    b=[]
    h=len(a)
    w=len(a[0])
    for i in range(w):
        bi=[]
        for j in range(h):
            bi.append(a[j][i])
        b.append(bi)
    return b
b=tenti(a)
h=len(b)
w=len(b[0])
c=[]
for i in range(h):
    if b[i]==["."]*w:
        continue
    c.append(b[i])
d=tenti(c)
for i in range(len(d)):
    for j in range(len(d[0])):
        if j==len(d[0])-1:
            print(d[i][j])
            break
        print(d[i][j],end="")

Submission status: Accepted

Solution code:
def grid_compression(H: int, W: int, A: list)->list:
    # 黒を含む行・列の番号を取得する。
    cols = []
    rows = []
    # まずは行番号
    for h in range(H):
        all_white = True
        for w in range(W):
            if A[h][w] == '#':
                all_white = False
                break
        if not all_white:
            rows.append(h)

    # 次に列番号
    for w in range(W):
        all_white = True
        for h in range(H):
            if A[h][w] == '#':
                all_white = False
                break
        if not all_white:
            cols.append(w)

    # rows/cols で示される行列の値を順番に突っ込んでく
    compressed = []
    for r in rows:
        compressed.append([])
        for c in cols:
            compressed[-1].append(A[r][c])

    return compressed


if __name__ == "__main__":
    H = 0
    H, W = map(int, input().split())
    A = [input() for _ in range(H)]
    ans = grid_compression(H, W, A)
    for row in ans:
        print(''.join(row))

Submission status: Accepted

Solution code:
# /user/bin/python
# -*- coding: utf-8 -*-
import sys 

h,w = map(int, sys.stdin.readline().rstrip().split())
As = []
for i in range(h):
  As.append(str(sys.stdin.readline().rstrip()))

cnt_h = [0] * h
cnt_w = [0] * w

for i in range(h):
  for j in range(w):
    if As[i][j] == '.':
      cnt_h[i] += 1
      cnt_w[j] += 1

idx_h = []
for i in range(h):
  if cnt_h[i] < w:
    idx_h.append(i)

idx_w = []
for i in range(w):
  if cnt_w[i] < h:
    idx_w.append(i)

for i in idx_h:
  for j in idx_w:
    print(As[i][j], end="")
  print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
a = [input() for i in range(H)]

rows = set()
cols = set()
for j in range(W):
    for i in range(H):
        if a[i][j] == '#':
            rows.add(i)
            cols.add(j)
for j in rows:
    for i in cols:
        print(a[j][i], end='')
    print('')

Submission status: Accepted

Solution code:
def ans():
  H, W = map(int,input().split())
  HW = [input() for _ in range(H)]
  HW = ["".join(hw) for hw in zip(*HW) if hw.count("#") > 0]
  HW = ["".join(hw) for hw in zip(*HW) if hw.count("#") > 0]
  print("\n".join(HW))
ans()

Submission status: Accepted

Solution code:
H, W = [int(x) for x in input().split()]
M = [list(input()) for _ in range(H)]

def flip(arr):

    x = len(arr[0])
    y = len(arr)

    newArr = [[None] * y for _ in range(x)]
    for xi in range(x):
        for yi in range(y):
            newArr[xi][yi] = arr[yi][xi]
    return newArr

def main():

    m = M
    m = list(filter(lambda row: any([n == '#' for n in row]), m))
    m = flip(m)

    m = list(filter(lambda row: any([n == '#' for n in row]), m))
    m = flip(m)

    for row in m:
        print(''.join(row))
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter
import numpy as np
H, W = map(int, input().split())
a = []
r_idx = []
c_idx = []
#a.shape = (H, W)
for i in range(H):
    line = list(input())
    ct = Counter(line).most_common()
    if not (ct[0][1] == W and ct[0][0] == "."):
        r_idx.append(i)
    a.append(line)
a = np.array(a).T
#a.shape = (W, H)
b = []
for i in range(W):
    ct = Counter(a[i]).most_common()
    if ct[0][1] == H and ct[0][0]==".":
        continue
    b.append(a[i])

b = np.array(b).T
c = []
for idx in r_idx:
    c.append(b[idx])

for i in range(len(c)):
    print("".join(c[i]))

Submission status: Accepted

Solution code:
import numpy as np
H,W = map(int,input().split())
l = []
for i in range(H):
    tmp = input()
    if tmp.count('.') != W:
        l.append(list(tmp))
    else:
      	H-=1
l = np.array(l).T.tolist()
ans = []
for i in l:
  if i.count('.') != H:
    ans.append(i)
for i in np.array(ans).T:
  print(''.join(i))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())

grid = []
for i in range(H):
    grid.append(input())

grid_h = list(filter(lambda h: any([_ == '#' for _ in h]), grid))
remove_list = []
for w in range(W):
    for i, g in enumerate(grid_h):
        if g[w] == '#':
            break
        if i == len(grid_h) - 1:
            remove_list.append(w)
grid_hw = []
for g in grid_h:
    s = ''
    for i, c in enumerate(g):
        if i not in remove_list:
            s += c
    grid_hw.append(s)
for g in grid_hw:
    print(g)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
a = [input() for i in range(H)]

a = ["".join(row) for row in zip(*a) if row.count("#") > 0]
a = ["".join(row) for row in zip(*a) if row.count("#") > 0]

print("\n".join(a))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a=[list(input()) for i in range(h)]
def vert(a):
    res=[]
    for i in range(len(a)):
        if all(x=="." for x in a[i]):
            res.append(i)
    return res
def hori(a):
    res=[]
    for i in range(len(a[0])):
        if all(a[j][i]=='.' for j in range(len(a))):
            res.append(i)
    return res

while True:
    v_res=vert(a)
    if not(len(v_res)==0):
        a= [a[i] for i in range(len(a)) if not i in v_res]
            
    h_res=hori(a)
    if not(len(h_res)==0):
        a=[[a[j][i] for i in range(len(a[0])) if not i in h_res] for j in range(len(a))]
    if len(h_res+v_res)==0:
        break
for ai in a:
    print(''.join(ai))

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a = [list(map(int, list(input().replace('.', '0').replace('#', '1')))) for _ in range(h)]

h_list, w_list = [], []
for i in range(h):
    if sum(a[i]) > 0:
        h_list.append(i)
for j in range(w):
    if sum([aa[j] for aa in a]) > 0:
        w_list.append(j)
for i in h_list:
    print(''.join(['.','#'][a[i][j]] for j in w_list))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc107/tasks/abc107_b


def check(m, p):
    for i in range(len(m)):
        if m[i][p] == "#":
            return(False)
    return(True)


h, w = [int(x) for x in input().split()]
a = []
b = []
for i in range(h):
    a.append(input())
for i in a:
    if i.count("#") != 0:
        b.append(i)
r = []
for i in range(w):
    if check(b, i):
        r.append(i)
for i in range(len(b)):
    tmp = list(b[i])
    for p in r:
        tmp[p] = "*"
    print("".join(tmp).replace("*", ""))

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
list_ = []
result = []
a = []
for i in range(H):
  tmp_set = list(input())
  if set(tmp_set) != {'.'}:
    list_.append(tmp_set)
    
for i in range(len(list_[0])):
  dot_ = 0
  a = [x[i] for x in list_]
  if set(a)!={'.'}:
    result.append(a)
    	
result = [list(x) for x in zip(*result)]
for i in result:
  print(''.join(i))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
a=['']*h
for i in range(h):
    a[i]=input()

row=[False]*h
col=[False]*w

for i in range(h):
    for j in range(w):
        if a[i][j]=="#":
            row[i]=True
            col[j]=True;

for i in range(h):
    if row[i]:
        for j in range(w):
            if col[j]:
                print(a[i][j],end="")
        print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
A = []
check = [0] * W

for i in range(H):
    row = input()
    if '#' not in row:
        continue
    else:
        for j in range(W):
            if row[j] == '#':
                check[j] += 1
        A.append(row)

for idx in range(len(A)):
    l_ = [a for i, a in enumerate(list(A[idx])) if check[i] != 0]
    A[idx] = ''.join(l_)

for l in A:
    print(l)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
a1 = []
for y in range(H):
    c = list(input())
    if '#' in c:
        a1.append(c)
a2 = list(zip(*a1))
a3 = []
for x in range(W):
    r = a2[x]
    if '#' in r:
        a3.append(r)
a4 = list(zip(*a3))
for r in a4:
    print(''.join(r))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
l=[]
for i in range(h):
    l.append(list(map(str,input())))

row=[False]*h
col=[False]*w
for i in range(h):
    for k in range(w):
        if l[i][k]=="#":
            row[i]=True
            col[k]=True
for i in range(h):
    if row[i]:
        for k in range(w):
            if col[k]:
                print(l[i][k], end="")
        print("")

Submission status: Accepted

Solution code:
H, W = map(int, input().split())

l = [input() for i in range(H)]

y = [False] * H
x = [False] * W

for i in range(H):
    flg = True
    for j in range(W):
        if l[i][j] != '.':
            flg = False
            break
    if flg:
        y[i] = True

for i in range(W):
    flg = True
    for j in range(H):
        if l[j][i] != '.':
            flg = False
            break
    if flg:
        x[i] = True

for i in range(H):
    if y[i]:
        continue
    for j in range(W):
        if x[j]:
            continue
        print(l[i][j], end='')
    print()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
L = ['']*H
for i in range(H):
  L[i] = input()
row = [False]*H
col = [False]*W
for i in range(H):
  for j in range(W):
    if L[i][j] == '#':
      row[i] = True
      col[j] = True
for i in range(H):
  if row[i] == True:
    for j in range(W):
      if col[j] == True:
        print(L[i][j],end = '')
    print()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
L = []
for i in range(H):
  L.append(input())
row = [False]*H
col = [False]*W
for i in range(H):
  for j in range(W):
    if L[i][j] == '#':
      row[i] = True
      col[j] = True
for i in range(H):
  if row[i] == True:
    for j in range(W):
      if col[j] == True:
        print(L[i][j],end = '')
    print()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
tmp=[]

for i in range(H):
  l=input()
  if '#' in l:
    tmp.append(l)

ans=[]
for l in zip(*tmp):
  if '#' in l:
    ans.append(''.join(l))

for l in zip(*ans):
  print(''.join(l))

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
board=[input() for _ in range(H)]

def transpose(b):
  L,C=len(b),len(b[0])
  ret=[]
  for c in range(C):
    s=''
    for l in range(L):
      s+=b[l][c]
    ret.append(s)
  return ret

tmp=transpose(board)
ans=[]
for l in tmp:
  if '#' in l:
    ans.append(l)

tmp=transpose(ans)
ans=[]
for l in tmp:
  if '#' in l:
    print(l)

Submission status: Accepted

Solution code:
h,w = map(int, input().split())
a = []
row_check = []
for i in range(h): #横が消える
    tmp = list(input())
    a.append(tmp)
    if '#' in tmp:
        row_check.append(i)
col_check = []
for i in range(w):
    columns =[]
    for j in range(h):
        columns.append(a[j][i])
    if '#' in columns:
        col_check.append(i)
res = []
for i in range(h):
    if i in row_check:
        tmp = []
        for j in range(w):
            if j in col_check:
                tmp.append(a[i][j])
        print(''.join(tmp))

Submission status: Accepted

Solution code:
H,W=(int(i) for i in input().split())
L=[]
for i in range(H):
    L.append(list(input()))

for x in L[:]:
    if '#' in x:
        continue
    else:
        L.remove(x)
L=list(map(list,zip(*L)))
for x in L[:]:
    if '#' in x:
        continue
    else:
        L.remove(x)
        
L=list(map(list,zip(*L)))
for i in range(len(L)):
    print(''.join(L[i]))

Submission status: Accepted

Solution code:
def solve(string):
    h, w, *a = string.split()
    h = int(h)
    w = int(w)
    rows = [sum([_c == "#" for _c in _a]) for _a in a]
    cols = [sum([_a[i] == "#" for _a in a]) for i in range(w)]
    ans = "\n".join(
        "".join([_c for __f, _c in zip(cols, _a) if __f]) for _f, _a in zip(rows, a) if _f)
    return ans


if __name__ == '__main__':
    n, w = map(int, input().split())
    print(solve('{} {}\n'.format(n, w) + '\n'.join([input() for _ in range(n)])))

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
a=[]
for i in range(h):
    a.append(input())
r=[False]*h
c=[False]*w

for i in range(h):
    for j in range(w):
        if a[i][j]=='#':
            r[i]=True
            c[j]=True
            
for i in range(h):
    if r[i]==True:
        for j in range(w):
            if c[j]==True:
                print(a[i][j],end='')
        print()

Submission status: Accepted

Solution code:
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys
import math

sys.setrecursionlimit(1000000)

INF = 10 ** 18

H, W = map(int, raw_input().split())

a = [raw_input() for _ in range(H)]
f1 = [False] * H
f2 = [False] * W

for i in range(H):
    hoge = True
    for j in range(W):
        if a[i][j] == '#':
            hoge = False
    f1[i] = hoge

for i in range(W):
    hoge = True
    for j in range(H):
        if a[j][i] == '#':
            hoge = False
    f2[i] = hoge

for i in range(H):
    if f1[i]:
        continue
    S = ""
    for j in range(W):
        if not f2[j]:
            S += a[i][j]
    print S

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
a=[input() for i in range(h)]
hi=[]
we=[]
def str_del(str,index):
    str = str[:index]+str[index+1:]
    return str

for i in range(h):

    if a[i] =='.'*w:
        we+=[i]

for i in range(w):
    memo=[]
    for j in range(h):
        memo+=a[j][i]
    if ''.join(memo) =='.'*h:
        hi+=[i]

for i in we[::-1]:
    a.pop(i)
for z in range(len(a)):
    for x in hi[::-1]:
        a[z]=str_del(a[z], x)

for i in a:
    print(i)

Submission status: Accepted

Solution code:
H, W = map(int, raw_input().split())
a = [raw_input() for _ in range(H)]

F = [False]*W
for y in range(H):
  for x in range(W):
    if a[y][x]=='#':
      F[x] = True
for y in range(H):
  if '#' in a[y]:
    l = ""
    for x in range(W):
      if F[x]:
        l += a[y][x]
    print l

Submission status: Accepted

Solution code:
def main():
    H, W = map(int, input().split())
    a = [list(input()) for _ in range(H)]

    row = [False] * H
    col = [False] * W
    for i in range(H):
        for j in range(W):
            if a[i][j] == "#":
                row[i] = True
                col[j] = True

    for i in range(H):
        if row[i]:
            for j in range(W):
                if col[j]:
                    print(a[i][j], end="")
            print()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
a = []
for i in range(h):
	a.append(list(input()))


temp1 = []
temp2 = []
for i in range(len(a)):
	ff = 0
	for j in range(len(a[i])):
		if a[i][j] == '.':
			continue
		ff = 1
	if ff == 0:
		temp1.append(i)
temp1.sort(reverse=True)
for i in range(len(a[0])):
	ff = 0
	for j in range(len(a)):
		if a[j][i] == '.':
			continue
		ff = 1
	if ff == 0:
		temp2.append(i)
temp2.sort(reverse=True)
for i in range(len(temp1)):
	a.pop(temp1[i])
for i in range(len(temp2)):
	for k in range(len(a)):
		a[k].pop(temp2[i])

for i in range(len(a)):
	s = ''
	for j in range(len(a[i])):
		s += a[i][j]
	print(s)

Submission status: Accepted

Solution code:
f=lambda s:zip(*[t for t in s if'#'in t])
for r in f(f(open(0).readlines())):print(*r,sep='')

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
a = [''] * H
for i in range(H):
	a[i] = input()
	
row = [False] * H
col = [False] * W 

for i in range(H):
	for j in range(W):
		if a[i][j] == '#':
			row[i] = True
			col[j] = True

for i in range(H):
	if row[i]:
		for j in range(W):
			if col[j]:
				print(a[i][j], end = '')
		print()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
Ass = [input() for _ in range(H)]

numHs = [0] * H
numWs = [0] * W
for i in range(H):
    for j in range(W):
        if Ass[i][j] == '#':
            numHs[i] += 1
            numWs[j] += 1

for i in range(H):
    if numHs[i] == 0: continue
    Bs = []
    for j in range(W):
        if numWs[j]:
            Bs += Ass[i][j]
    print(''.join(Bs))

Submission status: Accepted

Solution code:
height,width=map(int,input().split())
masu = []
for i in range(height):
    a = input()
    if "#" in a:
        masu.append(a)
N = [0]*width
for i in masu:
    for j in range(width):
        if i[j] == "." : N[j] += 1
number = []
for i in range(width):
    if N[i] != len(masu) : number.append(i)
result=[]
for i in range(len(masu)):
    a = ""
    for j in number:
        a+=masu[i][j]
    result.append(a)
for i in result:
    print(i)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 05:38:56 2019

@author: shinjisu
"""


# ABC 200点問題
import math


def getInt(): return int(input())


def getIntList(): return [int(x) for x in input().split()]


def zeros(n): return [0]*n


def dmp(x):
    global debug
    if debug:
        print(x)


debug = True


def getIntLines(n): return [int(input()) for i in range(n)]


def getIntMat(n):
    mat = []
    for i in range(n):
        mat.append(getIntList())
    return mat


def zeros2(n, m): return [zeros(m)]*n


def prob096():  # Maximum Sum
    X = getIntList()
    K = getInt()
    dmp((X, K))
    total = sum(X) - max(X) + max(X)*2**K
    return total


def prob097():  # Exponential
    X = getInt()
    dmp(X)
    if X == 1:
        return 1
    for n in range(X, 0, -1):
        dmp(n)
        for b in range(2, int(math.sqrt(X))+1):
            a = n
            exp = True
            while a > 1:
                if a % b != 0:
                    exp = False
                    break
                a //= b
            if exp:
                break
        if exp:
            break
    return n


def prob098():  # Cut and Count
    N = getInt()
    S = input()
    dmp((N, S))
    maxChCount = 0
    for i in range(1, N):
        before = S[:i]
        after = S[i:]
        dmp((before, after))
        chCount = 0
        for j in range(26):
            ch = chr(ord('a')+j)
            if ch in before and ch in after:
                chCount += 1
        maxChCount = max(maxChCount, chCount)
    return maxChCount


def prob099():  # Stone Momument
    a, b = getIntList()
    height = 0
    for i in range(b-a+1):
        height += i
    height -= b
    return height


def prob103():  # String Rotation
    S = input()
    T = input()
    for i in range(len(S)):
        S = S[1:] + S[0]
        dmp(S)
        if S == T:
            return 'Yes'
    else:
        return 'No'


def prob110():  # 1 Dimensional World's Tale
    N, M, X, Y = getIntList()
    cX = getIntList()
    cY = getIntList()
    dmp((N, M, X, Y))
    dmp(cX)
    dmp(cY)
    NW = 'No War'
    WA = 'War'
    if Y <= X:
        return WA
    cX.sort()
    cY.sort()
    dmp(cX)
    dmp(cY)
    if cX[-1] < cY[0] and \
            X < cY[0] and \
            cX[-1] < Y:
        return NW
    else:
        return WA


def prob109():  # Shiritori
    N = getInt()
    W = []
    for i in range(N):
        W.append(input())
    dmp(W)
    ALPHABET = [chr(i+ord('a')) for i in range(26)]
    NO = 'No'
    dmp(ALPHABET)
    used = set([W[0]])
    for i in range(1, N):
        dmp(used)
        if W[i] in used:
            return NO
        used.add(W[i])
        if W[i-1][-1] != W[i][0]:
            return NO
    return 'Yes'


def prob106():  # 105
    N = getInt()
    div8Count = 0
    for i in range(1, N+1):
        divCount = 0
        for j in range(1, i+1):
            #dmp(('i,j',i,j))
            if i % j == 0:
                divCount += 1
        dmp((i,divCount))
        if divCount == 8 and i % 2 == 1:
            div8Count += 1
    return div8Count


def prob107():  # Grid Compression
    H, W = getIntList()
    grid = []
    for i in range(H):
        grid.append(input())
    dmp((H,W))
    dmp(grid)
    WHITE = '.'
    i = 0
    while i < len(grid):
        for cell in grid[i]:
            if cell != WHITE:
                i += 1
                break
        else:
            grid.pop(i)
    dmp(grid)
    j = 0
    while j < len(grid[0]):
        for i in range(len(grid)):
            if grid[i][j] != WHITE:
                j += 1
                break
        else:
            for i in range(len(grid)):
                grid[i] = grid[i][:j] + grid[i][j+1:]
    return grid


def prob100():  # 
    return 0


debug = False  # True False
#print(prob107())
w = prob107()
for row in w:
    print(row)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
L = []
for i in range(H):
    L.append(list(input()))
dH = []
for i in range(H):
    if L[i].count('.') == W:
        dH.append(i)
dW = []
for i in range(W):
    flag = True
    for j in range(H):
        if L[j][i] == '#':
            flag = False
            break
    if flag:
        dW.append(i)
for i in range(H):
    if i in dH:
        continue
    ans = []
    for j in range(W):
        if not j in dW:
            ans.append(L[i][j])
    print(''.join(ans))

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    H, W = LI()
    A = []
    [A.append(S()) for i in range(H)]

    # まず横向きで削除していく
    rm_idx = []
    for idx, a in enumerate(A):
        if '#' not in a:
            rm_idx.append(idx)

    count = 0
    for idx, i in enumerate(rm_idx):
        del A[i-count]
        count += 1

    # 縦向きに探索
    rm_idx = []
    for w in range(W):
        if all(a[w] == '.' for a in A):
            rm_idx.append(w)

    count = 0
    for idx, i in enumerate(rm_idx):
        A = [a[:i-count] + a[i-count+1:] for a in A]
        count += 1

    for a in A:
        print(''.join(a))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
import collections
import itertools
import array
import inspect

# Set max recursion limit
sys.setrecursionlimit(1000000)


# Debug output
def chkprint(*args):
    names = {
        id(v): k
        for k, v in inspect.currentframe().f_back.f_locals.items()
    }
    print(', '.join(
        names.get(id(arg), '???') + ' = ' + repr(arg) for arg in args))


# Binary converter
def to_bin(x):
    return bin(x)[2:]


def li_input():
    return [int(_) for _ in sys.stdin.readline().split()]


def gcd(n, m):
    if n % m == 0:
        return m
    else:
        return gcd(m, n % m)


def gcd_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = gcd(v, L[i])

    return v


def lcm(n, m):
    return (n * m) // gcd(n, m)


def lcm_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = lcm(v, L[i])

    return v


# Width First Search (+ Distance)
def wfs_d(D, N, K):
    """
    D: 隣接行列(距離付き)
    N: ノード数
    K: 始点ノード
    """

    dfk = [-1] * (N + 1)
    dfk[K] = 0

    cps = [(K, 0)]
    r = [False] * (N + 1)
    r[K] = True
    while len(cps) != 0:
        n_cps = []
        for cp, cd in cps:
            for i, dfcp in enumerate(D[cp]):
                if dfcp != -1 and not r[i]:
                    dfk[i] = cd + dfcp
                    n_cps.append((i, cd + dfcp))
                    r[i] = True

        cps = n_cps[:]

    return dfk


# Depth First Search (+Distance)
def dfs_d(v, pre, dist):
    """
    v:  現在のノード
    pre: １つ前のノード
    dist: 現在の距離

    以下は別途用意する
    D: 隣接リスト(行列ではない)
    D_dfs_d: dfs_d関数で用いる，始点ノードから見た距離リスト
    """

    global D
    global D_dfs_d

    D_dfs_d[v] = dist

    for next_v, d in D[v]:
        if next_v != pre:
            dfs_d(next_v, v, dist + d)

    return


def sigma(N):
    ans = 0
    for i in range(1, N + 1):
        ans += i
    return ans


def comb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2, r + 1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p - 1, r, p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def bisearch(L, target):
    low = 0
    high = len(L) - 1
    
    while low <= high:
        mid = (low + high) // 2
        guess = L[mid]
        if guess == target:
            return True
        elif guess < target:
            low = mid + 1
        elif guess > target:
            high = mid - 1
    if guess != target:
        return False

# --------------------------------------------

dp = None


def main():
    H, W = li_input()
    S = [input() for _ in range(H)]

    i = 0
    while i < len(S):
        if S[i].count("#") == 0:
            S = S[:i] + S[i+1:]
        else:
            i += 1

    i = 0
    while i < len(S[0]):
        is_blank = True
        for j in range(len(S)):
            if S[j][i] == "#":
                is_blank = False
                break
        
        if is_blank:
            for j in range(len(S)):
                S[j] = S[j][:i] + S[j][i+1:]
        else:
            i += 1

    for s in S:
        print(s)


main()

Submission status: Accepted

Solution code:
H, W = input().split()
H = int(H)
W = int(W)

mas = []

for i in range(H):
    a = input()
    if a == '.'*W:
        continue
    mas.append(a)

delFlg = False
delcache = []
for i in range(W):
    delFlg = True
    for x in mas:
        if x[i] != '.':
            delFlg = False
            break
    if delFlg:
        delcache.append(i)
delcache.sort(reverse=True)

for i in delcache:
    for j,x in enumerate(mas):
        mas[j] = x[0:i] + x[i+1:]

for x in mas:
    print(x)