算法|ss dfs&bfs

  • 200.岛屿数量—1
  • 207.课程表—1
  • 547.省份数量
  • 695.岛屿的最大面积
  • 17.15.最长单词

200.岛屿数量—1

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
  let ans = 0;
  let m = grid.length;
  let n = grid[0].length;
  const dirs = [
    [1, 0],
    [-1, 0],
    [0, 1],
    [0, -1],
  ];
  const checkList = Array(m)
    .fill(0)
    .map(() => Array(n).fill(0));
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === "1" && checkList[i][j] === 0) {
        ans += bfs(i, j);
      }
    }
  }

  function bfs(i, j) {
    let count = 1;
    const queue = [];
    queue.push([i, j]);
    while (queue.length) {
      const [x, y] = queue.pop();
      for (let [dx, dy] of dirs) {
        let nextX = dx + x;
        let nextY = dy + y;
        if (
          nextX >= 0 &&
          nextX < m &&
          nextY >= 0 &&
          nextY < n &&
          grid[nextX][nextY] === "1" &&
          checkList[nextX][nextY] === 0
        ) {
          queue.push([nextX, nextY]);
          checkList[nextX][nextY] = 1;
        }
      }
    }
    return count;
  }
  return ans;
};
numIslands([
  ["1", "1", "1", "1", "0"],
  ["1", "1", "0", "1", "0"],
  ["1", "1", "0", "0", "0"],
  ["0", "0", "0", "0", "0"],
]);

207.课程表—1

// numCourses = 2, prerequisites = [[1,0]]
/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {boolean}
 */
var canFinish = function (numCourses, prerequisites) {
  const map = {};
  const nextMap = {};
  for (let [a, b] of prerequisites) {
    if (map[a] === undefined) {
      map[a] = 0;
    }
    if (nextMap[b] === undefined) {
      nextMap[b] = [];
    }
    map[a] += 1;
    nextMap[b].push(a);
    if (map[b] === undefined) map[b] = 0;
  }
  //
  const queue = [];
  for (let ch in map) {
    if (map[ch] === 0) {
      queue.push(ch);
    }
  }
  while (queue.length) {
    const cur = queue.shift();
    const nextCur = nextMap[cur];
    if (!nextCur) continue;
    for (let ch of nextCur) {
      map[ch] -= 1;
      if (map[ch] === 0) {
        queue.push(ch);
      }
    }
  }
  //   console.log(map);
  return Object.values(map).every((item) => item === 0);
};
canFinish(2, [
  [1, 0],
  [0, 1],
]);

547.省份数量

/**
 * @param {number[][]} isConnected
 * @return {number}
 */
// 思路
// 遍历一层, 对没有检查的可以看作是一个省份
// 递归dfs,对相连的城市都去dfs一下,然后设置对应的checklist为1,
// dfs的作用就是使相连的城市的checklist都为1
var findCircleNum = function (isConnected) {
  const n = isConnected.length;
  const checklist = Array(n).fill(0);
  let ans = 0;
  for (let i = 0; i < n; i++) {
    if (checklist[i] === 0) {
      dfs(i);
      ans += 1;
    }
  }
  //   console.log(ans);
  return ans;
  function dfs(idx) {
    checklist[idx] = 1;
    for (let j = 0; j < n; j++) {
      if (j !== idx && checklist[j] === 0 && isConnected[idx][j] === 1) {
        dfs(j);
      }
    }
  }
};
findCircleNum([
  [1, 0, 0],
  [0, 1, 0],
  [0, 0, 1],
]);
// [[1,0,0],[0,1,0],[0,0,1]]

695.岛屿的最大面积

/**
 * @param {number[][]} grid
 * @return {number}
 */
// 思路
// dfs的返回值 应该怎么定义
// 什么条件下返回
// 合格返回 1
// 不合格返回0
var maxAreaOfIsland = function (grid) {
  const m = grid.length;
  const n = grid[0].length;
  let ans = 0;
  let dirs = [
    [-1, 0],
    [1, 0],
    [0, 1],
    [0, -1],
  ];
  const checklist = Array(m)
    .fill(0)
    .map(() => Array(n).fill(0));
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (checklist[i][j] === 0 && grid[i][j] === 1) {
        ans = Math.max(ans, dfs(i, j));
      }
    }
  }
  //   console.log(ans);
  return ans;
  function dfs(x, y) {
    // 不符合条件的return 0
    if (
      x < 0 ||
      x >= m ||
      y < 0 ||
      y >= n ||
      grid[x][y] === 0 ||
      checklist[x][y] === 1
    ) {
      return 0;
    }
    let ans = 1;
    // 符合条件的返回ans
    checklist[x][y] = 1;
    for (let [dx, dy] of dirs) {
      ans += dfs(dx + x, dy + y);
    }
    return ans;
  }
};
maxAreaOfIsland([
  [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
  [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
  [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
]);
// [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]

17.15.最长单词

/**
 * @param {string[]} words
 * @return {string}
 */
// 思路 排序+dfs
// 单词降序
// 遍历单词组, 校验每一个单词
// 校验中采用递归写法
// 看字符串是否包含某个单词,如果包含了,则继续递归, idx=idx+temp.length
// 终止条件: idx的长度大于等于最长单词的长度
var longestWord = function (words) {
  // 降序排序 第一个word就是结果
  words.sort((a, b) =>
    a.length !== b.length ? b.length - a.length : a > b ? 1 : -1
  );
  for (let word of words) {
    if (isValid(word, 0)) {
      return word;
    }
  }
  return "";
  function isValid(word, idx) {
    // 终止条件
    if (idx >= word.length) return true;
    for (let i = 0; i < words.length; i++) {
      let temp = words[i];
      if (word === temp) continue;
      //   从idx位置截取到末尾 包含某个单词,则递归 下次的idx为当前idx+包含单词的长度
      if (word.substring(idx).indexOf(temp) === 0) {
        let res = isValid(word, idx + temp.length);
        if (res) return true;
      }
    }
    return false;
  }
};
console.log(
  longestWord(["cat", "banana", "dog", "nana", "walk", "walker", "dogwalker"])
);

// 输入: ["cat","banana","dog","nana","walk","walker","dogwalker"]
// 输出: "dogwalker"
// 解释: "dogwalker"可由"dog"和"walker"组成。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值