Skip to content

Instantly share code, notes, and snippets.

@Cvetomird91
Created December 30, 2020 13:16
Show Gist options
  • Save Cvetomird91/513a7577b33a29de6f3df50ffa3db409 to your computer and use it in GitHub Desktop.
Save Cvetomird91/513a7577b33a29de6f3df50ffa3db409 to your computer and use it in GitHub Desktop.
const limit = 100;
const sizing = 5000;
let visited = [];
let left = [];
let right = [];
let L = [[]];
let G = [[]];
let id = [[]];
const dr = [-1, 1, 0, 0];
const dc = [0, 0, -1, 1];
let V1 = 0;
let V2 = 0;
let N = 0;
let M = 0;
const scanf = require('scanf');
function dfs(cur) {
if(visited[cur]) {
return false;
}
visited[cur] = true;
for (let i = L[cur].length -1; i >= 0; i--) {
const to = L[cur][i];
if (left[to] == -1 || dfs(left[to])) {
right[cur] = to;
left[to] = cur;
return true;
}
}
return false;
}
function maxMatch() {
let ret = 0;
for (let i = 0; i < sizing; i++) {
left[i] = -1;
right[i] = -1;
}
let found = true;
while(found) {
for (let i = 0; i < sizing; i++) {
visited[i] = false;
}
found = false;
for(let i = 0;i < V1;++i)
if(right[i] == -1) found |= dfs(i);
}
for(let i = 0;i < V1;++i)
if(right[i] != -1) ++ret;
return ret;
}
function setUpArraySize() {
for (let i = 0; i < limit; i++) {
G[i] = [];
id[i] = [];
}
for (let x = 0; x < sizing; x++) {
L[x] = [];
}
}
setUpArraySize();
N = scanf('%d');
M = scanf('%d');
for(let i = 0; i < N;++i) {
for(let j = 0; j < M; ++j) {
G[i][j] = scanf("%d");
}
}
for(let i = 0; i < N;++i) {
for(let j = 0; j < M; ++j) {
if ((i + j) % 2 == 0) {
id[i][j] = V2++;
} else {
id[i][j] = V1++;
}
}
}
for(let i = 0; i < N;++i) {
for(let j = 0; j < M; ++j) {
if (!((i + j) % 2 == 0)) {
for(let k = 0;k < 4;++k) {
const r = i + dr[k];
const c = j + dc[k];
if (r >= 0 && r < N && c >= 0 && c < M && G[r][c] != G[i][j]) {
L[id[i][j]].push(id[r][c]);
}
}
}
}
}
if(maxMatch() < V1) {
printf("-1\n");
} else {
for(let i = 0, cont = 0; i < N; ++i){
for(let j = 0;j < M;++j){
if (!((i + j) % 2 == 0)) {
for(let k = 0;k < 4;++k) {
const r = i + dr[k];
const c = j + dc[k];
if (r >= 0 && r < N && c >= 0 && c < M && id[r][c] == right[id[i][j]]) {
++cont;
G[i][j] = cont;
G[r][c] = cont;
}
}
}
}
}
for(let i = 0;i < N;++i){
let output = '';
for(let j = 0;j < M;++j){
output = output.concat(G[i][j] + ' ');
}
if (output != '') {
console.log(output);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment