Open LeeeeeeM opened 5 years ago
经常用这个方法获取一张图片的图形数。 通过让canvas读取图片获取图片像素矩阵,从而获取图形个数。
const list = [{
id: 1,
name: '江苏',
children: [{
id: 11,
name: '南京',
children: [{
id: 111,
name: '栖霞区'
}]
}]
},
{
id: 2,
name: '山东',
children: [{
id: 21,
name: '济南',
children: [{
id: 211,
name: '历下区'
},
{
id: 212,
name: '城中区'
}]
}]
}];
// 实现一个方法,可以展开该数组[{id: 1, name: '江苏'}, {id: 11, name: '南京'}, ...]
// reduce解法
function flatten (array) {
return array.reduce(
(sum, item) => {
sum.push({
id: item.id,
name: item.name
})
return Array.isArray(item.children) ? sum.concat(flatten(item.children)) : sum.concat([])
}, []
)
}
// dfs解法
function flatten (array) {
const list = []
let item
while(item = array.shift()) {
list.push({
id: item.id,
name: item.name
})
if (item.children) {
array = item.children.concat(array)
}
}
return list
}
// bfs解法
function flatten(array) {
const list = []
while(item = array.shift()) {
list.push({
id: item.id,
name: item.name
})
if (item.children) {
array = array.concat(item.children)
}
}
return list
}
// 普通递归做法
function flatten (array) {
if (!array.length) return []
let list = []
while (item = array.shift()) {
list.push({
id: item.id,
name: item.name
})
if (item.children) {
list = list.concat(flatten(item.children))
}
}
return list
}
const aa = flatten(list)
console.log(aa)
// 获取矩阵中最大连续的块。例如[ // [1, 0, 1, 0, 1], // [1, 1, 0, 1, 1], // [0, 1, 0, 0, 1], // [0, 1, 0, 0, 0], // [0, 1, 0, 0, 0], // ]最大连续块个数为6。