grid <- expand.grid(x = 1:10, y = 1:10)
x <- grid$x
y <- grid$y
z <- (x + y - 1) * (x + y - 2) / 2 + y

n <- 6


dim(x) <- c(10, 10)
dim(y) <- c(10, 10)
dim(z) <- c(10, 10)


colours <- matrix("blue", 10, 10)




plot(x, y, col = colours, cex = 3, bty = "l", 
     xlab = "", ylab = "", xlim=c(0, 11), ylim = c(0, 11))
text(x, y, z, col = colours, cex = 0.7)

colours[x + y <= n + 1] <- "green"
colours[y <= x & x + y > n +1 & x <= n] <- "red"


plot(x, y, col = colours, cex = 3, bty = "l", 
     xlab = "", ylab = "", xlim=c(0, 11), ylim = c(0, 11))
text(x, y, z, col = colours, cex = 0.7)

temp <- sort(z[x + y > n + 1 & x <= n & y <= x])
tz <- t(z)

tz[x <= y & y <= n] <- 1 : z[1, n]
zTrans <- t(tz)
zTrans[y > x & x + y <= n +1] <- temp

coloursTrans <- matrix("blue", 10, 10)

coloursTrans[y <= x & x <= n] <- "green"
coloursTrans[y > x & x + y <= n +1 & y <= n] <- "red"

plot(x, y, col = coloursTrans, , cex = 3, bty = "l", 
     xlab = "", ylab = "", xlim=c(0, 11), ylim = c(0, 11))
text(x, y, zTrans, col = coloursTrans, cex = 0.7)