Minimum Swaps to Arrange a Binary Grid LeetCode solution in JavaScript
1var minSwaps = function (grid) {2const arr = [];3let count = 0;45for (let row of grid) {6arr.push(row.lastIndexOf(1));7}89function swap(i, j) {10[arr[i], arr[j]] = [arr[j], arr[i]];11count++;12}1314for (let i = 0; i < arr.length; i++) {15// if num <= i pass b/c it's its correct spot16if (arr[i] <= i) continue;17let j = i;1819// scan forward looking for a num <= i20while (arr[j] > i) {21j++;22if (j >= arr.length) return -1;23}2425// swap as you move back to the right spot26for (let k = j; k > i; k--) {27swap(k, k - 1);28}29}30return count;31};