Skip to content

Latest commit

 

History

History
49 lines (41 loc) · 1.46 KB

780.到达终点.md

File metadata and controls

49 lines (41 loc) · 1.46 KB

780.到达终点

/*
 * @lc app=leetcode.cn id=780 lang=typescript
 *
 * [780] 到达终点
 */

// @lc code=start
function reachingPoints(sx: number, sy: number, tx: number, ty: number): boolean {}
// @lc code=end

解法 1: 反向计算

function reachingPoints(sx: number, sy: number, tx: number, ty: number): boolean {
  while (tx && ty && sx !== tx && sy !== ty) {
    if (tx > ty) tx = tx % ty
    else ty = ty % tx
  }

  if (tx === sx && ty === sy) return true
  else if (tx === sx && ty > sy) return (ty - sy) % tx === 0
  else if (ty === sy && tx > sx) return (tx - sx) % ty === 0
  else return false
}

Case

test.each([
  { input: { sx: 6, sy: 5, tx: 11, ty: 16 }, output: true },
  { input: { sx: 4, sy: 2, tx: 2, ty: 4 }, output: false },
  { input: { sx: 5, sy: 10, tx: 15, ty: 10 }, output: true },
  { input: { sx: 1, sy: 8, tx: 4, ty: 15 }, output: false },
  { input: { sx: 1, sy: 6, tx: 11, ty: 10 }, output: true },
  { input: { sx: 3, sy: 3, tx: 12, ty: 9 }, output: true },
  { input: { sx: 1, sy: 1, tx: 3, ty: 5 }, output: true },
  { input: { sx: 1, sy: 1, tx: 2, ty: 2 }, output: false },
  { input: { sx: 1, sy: 1, tx: 1, ty: 1 }, output: true },
])('input: sx = $input.sx, sy = $input.sy, tx = $input.tx, ty = $input.ty', ({ input: { sx, sy, tx, ty }, output }) => {
  expect(reachingPoints(sx, sy, tx, ty)).toEqual(output)
})