LeeeeeeM / blog

daily blog
0 stars 0 forks source link

疯狂搞递归。 #32

Open LeeeeeeM opened 5 years ago

LeeeeeeM commented 5 years ago

// 获取矩阵中最大连续的块。例如[ // [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。

function getBlock(array, i, j) {
  if (array[i][j] === 0) return 0
  let sum = 0
  array[i][j] = 0
  sum++

  if (array[i] && array[i][j - 1] === 1) {
    sum += getBlock(array, i, j - 1)
  }

  if (array[i] && array[i][j + 1] === 1) {
    sum += getBlock(array, i, j + 1)
  }

  if (array[i + 1] && array[i + 1][j] === 1) {
    sum += getBlock(array, i + 1, j)
  }

  if (array[i - 1] && array[i - 1][j] === 1) {
    sum += getBlock(array, i - 1, j)
  }

  return sum
}

function getMaxBlocks(bytesArray) {
  const blocks = []
  for (let i = 0; i < bytesArray.length; i++) {
    for (let j = 0; j < bytesArray[i].length; j++) {
      let block = getBlock(bytesArray, i, j)
      if (block > 0) {
        blocks.push(block)
      }
    }
  }
  return Math.max(...blocks)
}

const a = getMaxBlocks(
  [
    [1, 1, 1, 0, 1],
    [1, 1, 0, 1, 1],
    [0, 1, 0, 0, 1],
    [0, 1, 1, 0, 0],
    [0, 1, 0, 0, 0],
  ]
)

console.log(a)
LeeeeeeM commented 5 years ago

经常用这个方法获取一张图片的图形数。 通过让canvas读取图片获取图片像素矩阵,从而获取图形个数。

LeeeeeeM commented 5 years ago

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)