初级7主要讲的内容有:
1、认识并查集
2、岛问题
3、前缀树的介绍及功能扩充
4、贪心策略,字典序问题
岛问题的经典解法:
一个矩阵中只有0和1两种值,每个位置都可以和自己的上、下、左、右四个位置相连,如果有一片1连在一起,这个部分叫做一个岛。求一个矩阵中有多少个岛?
import numpy as np
def island(amatrix):
n = amatrix.shape[0]
m = amatrix.shape[1]
island_num = 0
for i in range(n):
for j in range(m):
if amatrix[i, j]==1:
infectprocess(i, j, amatrix)
island_num += 1
return island_num
def infectprocess(i, j, amatrix):
if i < 0 or i > amatrix.shape[0]-1 or j < 0 or j > amatrix.shape[1]-1 or amatrix[i, j]!=1:
return
amatrix[i, j]=2
infectprocess(i-1, j, amatrix)
infectprocess(i+1, j, amatrix)
infectprocess(i, j-1, amatrix)
infectprocess(i, j+1, amatrix)
casea = np.array([[0,0,1,0,1,0],[1,1,1,0,1,0],[1,0,0,1,0,0],[0,0,0,0,0,0]])
print(casea)
print(island(casea))
[[0 0 1 0 1 0]
[1 1 1 0 1 0]
[1 0 0 1 0 0]
[0 0 0 0 0 0]]
3
前缀树的实现:
查是否有字符串以xx开头
增加数据项:
有多少个字符串以它结尾(xx字符串出现的次数)
每一个节点被划过了多少次(以xx为前缀的字符串出现的次数)
class trienode:
def __init__(self):
self.path = 0
self.end = 0
self.map = [None for i in range(26)]
class trietree:
def __init__(self):
self.root = trienode()
def insert(self, word):
if word==None:
return
node = self.root
for i in word:
index = ord(i) - ord('a') #ord将字符转化为ascii码
if node.map[index] == None:
node.map[index] = trienode()
node.map[index].path += 1
node = node.map[index]
node.end += 1
def search(self, word): #查xx字符串出现的次数
if word==None:
return 0
node = self.root
for i in word:
index = ord(i) - ord('a')
if node.map[index]==None:
return 0
node = node.map[index]
return node.end
def startwith(self, word): #以xx为前缀的字符串出现的次数
if word==None:
return 0
node = self.root
for i in word:
index = ord(i) - ord('a')
if node.map[index] == None:
return 0
node = node.map[index]
return node.path
def delete(self, word):
if word==None:
return
node = self.root
for i in word:
index = ord(i) - ord('a')
node.map[index].path -= 1
if node.map[index].path == 0:
node.map[index] = None
return
node = node.map[index]
node.end -= 1
newtree = trietree()
newtree.insert('abc')
newtree.insert('abc')
newtree.insert('bef')
newtree.insert('bc')
newtree.insert('abd')
newtree.delete('abc')
print(newtree.search('abc'))
print(newtree.startwith('b'))
print(newtree.startwith('be'))
1
2
1